Ask Your Question
1

Why doesn't array_search function properly on multidimensional arrays like it does for other accepted solutions?

asked 2022-12-13 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-05-23 17:00:00 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-13 11:00:00 +0000

Seen: 7 times

Last updated: May 23 '21