1

I have a function inside of a class, every time I use I got error undefined function in_array_r() inside of foreach. But when I use it outside of the class as normal function it works. I want to use this inside of the class so I will not call in every page.

public function in_array_r($needle, $haystack, $strict = false) {
        foreach ($haystack as $item) {
            if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
                return true;
            }
        }
        return false;
    }

2 Answers 2

1

The function is recursive - it's calling itself. When you put it inside a class (as a method), you need to update the reference to in_array_r() within the method body.

This:

. . .(is_array($item) && in_array_r($needle, . . .

Becomes:

. . .(is_array($item) && $this->in_array_r($needle, . . .
Sign up to request clarification or add additional context in comments.

Comments

1

You need to assign the method to the object.

$this->in_array_r();

1 Comment

also you can improve your code and return false if $haystack false, as a simple check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.