If you're looking for a specific id
index specifically, then in_array()
isn't going to do what you want to do, since that function operates on values rather than keys. That means that if you were searching for a specific id, the function would return true if a different key happened to have the value you were searching for, even if there was no id
with that value.
If your multidemensional array is always just going to be an array of one dimensional arrays, then you could do something like the following:
function find_kv_pair($array, $key, $value) {
foreach($array as $arr) {
if ( is_array($arr) &&
array_key_exists($key, $arr) &&
$arr[$key] == $value;
) {
return $arr;
}
}
return false;
}
You would then call it like so:
if (find_kv_paid($my_array, "id", 123)) !== false) {
// do something with the returned array
} else {
// nothing found. handle the condition
}
If the array has an array with a key/value pair of 'id' => 123
, then that sub-array would be returned and processed, otherwise you would get a false and you could handle it accordingly.
This function takes your array of sub-arrays, and checks each sub-array to see if it has an id
key matching your search value. If one is found, it returns that sub-array, or false if no sub-array has it. Modify it to return whatever you like if you don't just want the whole array.
If your sub-arrays can themselves have sub-arrays, you can just rewrite the function to be recursive.