1

I have an array that has "formname" in it as a $key. When I execute the following function:

    function in_array_r($needle, $arr, $strict = true) {
    $form_id = $lead['form_id'];
                $user_id = $lead['id'];
                $attachments = array();
$arr=get_defined_vars();
$needle="formna1me";
    foreach ($arr as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            echo "found"; exit;
        }
    }

    echo "notfound"; exit;
}

It returns "found" as it should. But if I change the $needle to $needle = "bbrubrcuyrfbur" it also returns found. It is simply always returning found? Not sure what is wrong.

7
  • Why do you start off with a foreach()..? Commented Oct 29, 2012 at 16:01
  • Using concept from stackoverflow.com/questions/4128323/… Commented Oct 29, 2012 at 16:03
  • 2
    You are using || instead of && in your if statement. Commented Oct 29, 2012 at 16:03
  • Added the full function. Commented Oct 29, 2012 at 16:05
  • @Jrod - when change to && then it always returns "notfound" Commented Oct 29, 2012 at 16:06

2 Answers 2

1

You are calling the function recursively. Even when you call the function with needle as bbrubrcuyrfbur, in the if condition the function is called recursively with needle as formna1me.

Inside the first recursion, $arr=get_defined_vars(); will read the value of $needle as formna1me. Then $needle will be reassigned formna1me and the if condition will match formna1me from $needle with the one in $args.

Lines 2 to 6 should probably not be in that function.

0
0

is_array supposed to work like below you are checking the item in is_array instead of array

$yes = array('this', 'is', 'an array');

echo is_array($yes) ? 'Array' : 'not an Array';

what is_array is doing is that

is_array — Finds whether a variable is an array

as your comment

tofind that the value is in array try in_array — Checks if a value exists in an array

$arr = array("Mac", "NT", "msc", "Linux");
if (in_array("Linux", $arr)) {
   echo 'yes it is';
}
2
  • @Chris this is probably one mistake you are doing Commented Oct 29, 2012 at 16:06
  • I am not trying to find out if it is an array, I am trying to find if variable is IN an array. Commented Oct 29, 2012 at 16:08

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.