Check if array key exists in a multidimentional array

I have an array that’s generated using mysql like this:

[php]$conn = connect();
$stmt = $conn->prepare("select id, type, status from arraytest");
$stmt->execute();
$myArray = $stmt->fetchAll();[/php]

When I do print_r($myArray), I get this:

[php]Array ( [0] => Array ( [id] => 3 [0] => 3 [type] => 0 [1] => 0 [status] => 0 [2] => 0 ) [1] => Array ( [id] => 6 [0] => 6 [type] => 0 [1] => 0 [status] => 1 [2] => 1 ) ) [/php]

I can also access the array this way:

[php] echo $myArray[0][0]. ’ ’ . $myArray[0][1]. ’ ’ . $myArray[0][2];
echo ‘
’;
echo $myArray[1][0]. ’ ’ . $myArray[1][1]. ’ ’ . $myArray[1][2];
[/php]
The table data is simple:

[php] “id” “type” “status”
“3” “0” “0”
“6” “0” “1”[/php]

I need to run the array against a while loop and check if id from the array matches the $i. But how is this done with an array like this? I cant figure out? Can you please help?

[php] while ($i <= 10) {
echo $i;
echo ((array_key_exists($i,$myArray)) ? ’ OK
’ : ’ Fail
'); // I need to check if $i == id from the array.
$i++;
echo ‘
’;
}[/php]

[php]Expected Output

1 Fail
2 Fail
3 OK
4 Fail
5 Fail
6 OK
//and so on[/php]

I actually have issues following what you are trying to do. On one hand, you want to effectively filter out your results for id being a certain values. On the other hand, you mention array_key_exists, which is not that behaviour at all - this function merely checks if the key is defined, not its value!

For the first behaviour, you may want something like this:

[php]function in_results($id,$array) {
foreach ($array as $v) {
if (isset($v[‘id’]) && $v[‘id’] === $id) {
return $v;
}
}
return false;
}[/php]

This will return the ID row if it exists, and will return false otherwise. This allows you to then use the function and check its return value, though if you’re doing this, you may be better off doing it from the DB side - returning a lot of data is an expensive process.

Sponsor our Newsletter | Privacy Policy | Terms of Service