Get key of multidimensional array?

Get key of multidimensional array?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting Numeric Keys from Multidimensional Arrays in PHP

When working with multidimensional arrays, a common stumbling block is identifying the top-level numeric indices without iterating through every element to check its type. In your specific scenario, you have a list of photo metadata where each item contains id, gallery_id, and picture. You need to isolate the keys 0 through 6 representing the order or sequence of these records.

The most direct approach in modern PHP is to use the array_keys() function combined with filtering, but simply calling it returns all keys regardless of their nature. If your array contains both string and integer keys at the top level, array_keys() will return a mix. To strictly retrieve only the numeric indices like 0, 1, 2, you must filter the result based on the data type of the key itself.

Here is a robust pattern using array_filter to isolate numeric keys:

$numericKeys = array_filter(
    array_keys($array),
    fn($key) => is_int($key) || ($key === '' && !empty($array)) // Handles edge cases with empty strings if present
);

However, this can be brittle if the array contains string keys that are numerically equivalent to integers (e.g., '1' vs 1). A safer method that guarantees you get only strictly integer indices is to cast the keys and check their type:

$numericKeys = array_values(
    array_keys($array, null, true) // The third argument 'true' forces associative retrieval
);

// Or more explicitly filtering for integers
$keys = [];
foreach (array_keys($array) as $k) {
    if (is_int($k)) {
        $keys[] = $k;
    }
}

If your goal is to verify that the array maintains a contiguous sequence starting from zero, you might want to compare the count of elements against the last numeric key. In a well-formed list like yours, array_keys() followed by a check for contiguous integers ensures no gaps exist between index 0 and N.

Handling Associative Arrays vs. Numeric Indices

It is crucial to distinguish between retrieving keys that are integers versus retrieving values associated with specific keys. Sometimes developers confuse array_column() logic with key extraction. If you need the actual numeric indices for iteration purposes, such as looping backwards or accessing elements by position directly, converting the filtered keys using array_values() creates a new array containing only those integers:

$onlyNumericIndices = array_values(array_filter(
    array_keys($array),
    fn($key) => is_numeric($key) && !str_contains((string)$key, '.') // Ensure it's not a float key like 1.5
));

In your specific dataset, since every top-level element is an object-like array starting at 0, the keys are strictly integers. If you were to add an item manually without incrementing the index (e.g., inserting something at key 10), the automatic counting would break. PHP arrays are hash tables; they do not maintain order by default. Therefore, relying on key existence is often safer than assuming sequential numbering unless you explicitly reconstruct the array with array_values().

Trade-offs and Performance Considerations

Using array_keys() creates a new array containing all keys. For massive datasets where performance is critical, this duplication might seem unnecessary. However, for typical application data structures like the gallery list you provided, the overhead is negligible. The primary trade-off here is readability versus complexity. A simple foreach loop checking is_int($key) is often more readable than chaining array_filter functions with closures, especially if you are already iterating to process the data anyway.

If you need to ensure the array is strictly indexed from 0 to N-1, consider using array_values() on a filtered list of keys or simply reconstructing the array if gaps are not acceptable in your business logic. This ensures that $array[0] always holds the first element, regardless of how the data was inserted previously.

For more complex scenarios involving large-scale data manipulation or strict schema enforcement, you might look into dedicated libraries or tools that enforce indexed structures, but for standard PHP application logic, careful use of is_int() checks remains the industry standard for validating numeric indices.

Our network