How to flatten an array in PHP


In a recent Kohana project, I came across a somewhat odd PHP scenario – I had a multidimensional array that I needed to compress to a single dimensional array, but retaining all of the non array values. Basically, I need to make this change:

Array
    (
        to => Array
            (
                0 => stevep
                1 => bobw
            )
        bcc => Array
            (
                0 => paulj
            )
    )

Array
    (
        0 => stevep
        1 => bobw
        2 => paulj
    )

I looked around a bit for an existing PHP snippet to do just this, but they were all overly complex and used recursive callback functions. I had a feeling I could pull this off in a much more clean fashion. I toyed around a bit with the array functions and the ArrayObject library, and this is what I settled with:

$new_array = new ArrayObject();
array_walk_recursive($old_array, array($new_array, 'offsetSet'));
$flattened_array = array_keys($new_array->getArrayCopy());

The big drawback is the way ArrayObect::offsetSet() accepts its parameters, compared to how array_walk_recursive() sends the callback parameters; they are reversed. This causes the values to become keys, which has the effect of canceling out duplicate values. If your script needs duplicate values to remain intact, then this solution won’t work for you. Otherwise, it should work out just fine.

, ,

  1. No comments yet.
(will not be published)