I need to get the keys from values that are duplicates. I tried to use array_search and that worked fine, BUT I only got the first value as a hit.
I need to get both keys from the duplicate values, in this case 0 and 2. The search result output as an array would be good.
Is there a PHP function to do this or do I need to write some multiple loops to do it?
$list[0][0] = "2009-09-09";
$list[0][1] = "2009-05-05";
$list[0][2] = "2009-09-09";
$list[1][0] = "first-paid";
$list[1][1] = "1";
$list[1][2] = "last-unpaid";
echo array_search("2009-09-09",$list[0]);
The following combination of function calls will give you all duplicate values:
You want array_keys with the search value
which will return an array of the keys with the specified value, in your case [0, 2]. If you want to find the duplicates as well, you can first make a pass with array_unique, then iterate over that array using array_keys on the original; anything which returns an array of length > 1 is a duplicate, and the result is the keys in which the duplicates are stored. Something like...
The PHP manual states in the
Return Value
section of thearray_search()
function documentation that you can usearray_keys()
to accomplish this. You just need to provide the second parameter:In
array_search()
we can read:You can achieve that using
array_search()
by usingwhile
loop and the following workaround:Source: cue at openxbox at php.net
For one-multidimensional array, you may use the following function to achieve that (as alternative to
array_keys()
):Source: robertark, php.net