0

I seem to be having a problem checking if a string exists in my array. There is probably a really obvious answer to my question do forgive me but I'm new to PHP.

Anyway here is my code:

while($row = mysql_fetch_assoc($result))
{
    $result_array[] = $row;
}

if (in_array("496891", $result_array)) 
{
echo "true";
}
else
{
echo "false";
}

The array looks like this:

Array ( [0] => Array ( [ID] => 496891 ) [1] => Array ( [ID] => 1177953 )) 

My code always echoes false. Anyone know what I'm doing wrong?

Thanks

1
  • 2
    in_array only checks the "first" level of a array. You have a multidimensional one. Commented Jun 22, 2012 at 8:01

3 Answers 3

3

You have a nested array and must check against each item like so:

function in_multidimensional_array($val, $array) {
  foreach($array as $key => $value) {
     if (in_array($val, $array[$key])) {
        return true;
     }  
  }
  return false;
}

Now you can check if the value 496891 exists using:

if(in_multidimensional_array('496891', $result_array)) {
   print 'true';
} else {
   print 'false';
}
Sign up to request clarification or add additional context in comments.

Comments

2

Krister's solution only works if you only have one row in your MySQL-loop. This would check against all the results.

while($row = mysql_fetch_assoc($result))
{
    $result_array[] = $row;
}

$found = false;
foreach ($result_array as $v) {
    if (in_array("496891", $v)) {
        $found = true;
    }
}

if ($found == true)
    echo 'true';
else
    echo 'false';

Comments

0

You are searching for a string, but your array is holding numeric values. You would need to make sure that you insert it specifically as a string to get it to return true, or each field as a string prior to the search.

Comments

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.