I have an associative array that is many levels deep. I want to convert it to an indexed array (i.e. remove the key names). I don't want to flatten it; I want it to remain a nested array with all of the values intact. What's the best way to accomplish this?

Dani AI

Generated

In PHP, arrays are ordered maps. If your keys are strings, you cannot reliably access elements by numeric offset; you need to actually drop the keys. The simplest way to do that without flattening is to apply array_values() at every level so order is preserved and keys are reindexed from 0 at each depth.

Here is an in-place approach that avoids building a full second copy of the structure, which helps with memory on large trees:

function reindexDeep(&$a) {
    if (!is_array($a)) return;
    foreach ($a as &$v) {
        reindexDeep($v);
    }
    unset($v); // important when using foreach by reference
    $a = array_values($a);
}

Usage:

reindexDeep($data); // $data is modified in place

Notes:

  • Time complexity is O(n). Order is preserved; only the keys are dropped at each level.
  • Mixed numeric keys will be renumbered starting at 0. Scalars and non-arrays are left as-is.
  • Recursion depth depends on your nesting; for extremely deep structures, consider an iterative post-order traversal. Most practical configs handle typical nesting fine.

See the PHP docs for details on array_values, foreach by reference, and how PHP arrays behave.

Recommended Answers

All 3 Replies

Don't think you have to, you can just access it by index as well.

I quickly put together this recursion function.

function assoc2indexedMulti($arr) {

    // initialize destination indexed array
    $indArr = array();

    // loop through source
    foreach($arr as $val) {

        // if the element is array call the recursion
        if(is_array($val)) {

            $indArr[] = assoc2indexedMulti($val);

        // else add the value to destination array
        } else {

            $indArr[] = $val;
        }
    }

    return $indArr;
}

Tested it on a small array, I hope it works OK on your array. If the array is large it might be an issue since it doubles the memory requirement.

Thanks, that worked! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.