The array_search
function is not designed to work with multi-dimensional arrays. It only works with one-dimensional arrays. When you use array_search
on a multi-dimensional array, it will only search the first level of the array and return the index of the first matching element it finds, even if the matching element is in a sub-array.
For example, if you have a multi-dimensional array like this:
$array = array(
array('apple', 'orange'),
array('banana', 'pear'),
array('grapefruit', 'orange')
);
And you try to search for the value 'orange' using array_search
:
$key = array_search('orange', $array);
It will return the index of the first sub-array that contains 'orange', which is 0. It will not return the index of the second occurrence of 'orange' in the third sub-array.
To search for values in multi-dimensional arrays, you can use a recursive function that searches all levels of the array. Alternatively, you can flatten the multi-dimensional array into a one-dimensional array using the array_merge
function, and then use array_search
on the flattened array.
Asked: 2022-12-13 11:00:00 +0000
Seen: 7 times
Last updated: May 23 '21