Navigating Mixed Arrays in PHP: Getting Values by Numeric Index
In PHP, arrays are flexible structures that can hold both string keys and integer keys simultaneously. When you iterate over such a collection using standard functions like foreach, the engine iterates based on the keys as they exist in the array's internal structure. However, there is often a need to access elements strictly by their ordinal positionâtreating the array as a list regardless of its associative keys.
Consider a scenario where you have an array populated with mixed keys:
$array = ['foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum'];
If your goal is to retrieve 'bar', then 'bin', and finally 'ipsum' by passing indices 0, 1, and 2 respectively, you are asking for the element at a specific offset from the beginning of the list. This requires ignoring the associative keys entirely and treating the array as a zero-indexed sequence.
The native function designed specifically for this purpose is array_search, but it works in reverse (finding the key given a value), so that isn't applicable here. Instead, PHP provides array_values. When you pass your mixed array to array_values, it strips away all keys and returns a new array containing only the values, reindexed from 0 upwards.
$numericArray = array_values($array);
echo $numericArray[0]; // Outputs: bar
echo $numericArray[1]; // Outputs: bin
echo $numericArray[2]; // Outputs: ipsum
This approach is robust because it guarantees that the returned structure is purely numeric. However, creating a new array variable every time you need an item adds overhead and clutter to your code. A more direct solution exists within the standard array functions family if you are willing to accept a slight semantic nuance: array_slice.
If you know exactly which element you want based on its offset, you can use array_slice with a length of one. This function creates a slice of the array starting at the specified offset. Since array_slice returns an associative array (even when slicing from a numeric index), you still technically have to access the first key of the result set.
function getByOffset(array $data, int $index): mixed {
return current(array_slice($data, $index, 1));
}
echo getByOffset($array, 0); // bar
echo getByOffset($array, 1); // bin
echo getByOffset($array, 2); // ipsum
While this works, it involves creating a temporary sub-array just to extract the first element. This is generally less efficient than array_values if you are planning to iterate over the whole list later, but it is perfectly acceptable for single-item retrieval when key preservation isn't required.
There is another critical consideration regarding performance: splicing or re-indexing an array with array_values inside a tight loop is expensive. If you find yourself needing the nth element repeatedly in a loop, converting the entire mixed array to a purely numeric one once at the start of the process is the optimal strategy.
// Convert once
$indexedArray = array_values($array);
// Now access by index directly
echo $indexedArray[0];
This pattern transforms your data into a predictable format, allowing subsequent operations to treat it as a standard list without worrying about sparse keys or mixed types. The trade-off is the initial memory cost of creating the new array, but for most applications, this one-time allocation is negligible compared to the complexity saved later.
If you are working within the Laravel ecosystem, remember that Eloquent collections and generic arrays behave slightly differently regarding keys. While array_values works on standard PHP arrays, Laravel often encourages using collection methods like first() or get() with specific offsets if you are already handling data within a controller or service layer. However, for raw array manipulation, the native functions remain the most performant and clear choice.
Ultimately, while you could write a helper function to encapsulate this logic, PHP's standard library already offers tools to handle mixed arrays effectively. Understanding when to use array_values versus direct indexing is key to writing efficient code that respects the underlying data structure without unnecessary overhead.
