To learn the offset or array key for a specific array element in a given array turns out to be fairly easy, thanks to the extra search parameter that the always useful array_keys (return all the keys or a subset of the keys of an array) function offers us.

From the manual description: array array_keys ( array $input [, mixed $search_value = NULL [, bool $strict = false ]] ) – array_keys() returns the keys, numeric and string, from the input array. If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned.

Knowing this, we can now find exactly where a specific element sits by simply entering a search value when calling the array_keys function, which in practice would look something like this:

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
    [0] => 0
    [1] => 3
    [2] => 4

The above example shows us that the array element “blue” appears at offset 0, 3 and 4 in the source array.


Related Link: