PHP: Identify the Offset of a Specific Array Element CodeUnit 04 DEC 2012

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"));
/*
Array
(
    [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.

Nifty.

Related Link: http://www.php.net/manual/en/function.array-keys.php

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.