How to Access "n-th" Element of a PHP Array With Mixed Keys?

In PHP, to access the n-th offset of an array that has mixed keys (i.e. it has both, numeric and strings, keys), you can do either of the following:

Using array_keys()

You can use the array_keys() function to get an array of all keys of an existing array. From this array of keys, you can get the key at the "n-th" offset, and use that to access the array element mapped to that key.

For example, to access the second array element in an array that has mixed, out-of-sequence keys, you could do the following:

$arr = [3 => 'foo', 'bar' => 'baz', 1 => 'qux'];

// 1: get all array keys
$keys = array_keys($arr); // [3, 'bar', 1]

// 2: get offset
$key = $keys[1]; // 'bar'

// 3: access the offset
var_dump($arr[$key]); // 'baz'

You may specify a default offset by using null coalescing operator (??). This would return the right hand expression when the left expression does not exist or is null, for example, like so:

// PHP 7+
// ...

$key = $keys[10] ?? 1; // defaults to 1 when offset 10 doesn't exist

// ...

Similarly, starting with PHP 8, you may also throw an exception from the right hand expression, for example, like so:

// PHP 8+
// ...

$key = $keys[10]
    ?? throw new OutOfBoundsException('Key offset does not exist')
;

// ...

Using array_slice()

You can use the array_slice() function to extract a single array element, for example, like so:

$arr = [3 => 'foo', 'bar' => 'baz', 1 => 'qux'];

$elem = array_slice(
    $arr,
    1, // offset
    1, // length
    false // preserve keys? (default)
);

$key = key($elem); // 'bar'

var_dump($elem); // ['bar' => 'baz']
var_dump($elem[$key]); // 'baz'

Even though the last parameter to array_slice() is set to false, it still preserves string keys (as you can see in the example above). However, numeric keys are re-indexed. Therefore, for consistence's sake, maybe it would be better to set the last parameter (for preserving keys) to true (as it would preserve both, string and numeric, keys).

If the offset (i.e. second argument) specified to array_slice() does not exist, an empty array is returned:

$arr = [3 => 'foo', 'bar' => 'baz', 1 => 'qux'];

$elem = array_slice($arr, 10, 1, false);

$key = key($elem); // null

var_dump($elem); // []

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.