Archive for March, 2010

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.

, ,

No Comments

Upcoming Work

It’s now been over a month since I’ve written any articles. I’ve been busy lately with a number of activities, plus my regular job, and just haven’t had time to write much. I do have a few article ideas that I’ll be doing shortly, though, so this site isn’t quite dead yet.

I’ll be writing an article on best practices for creating new classes in PHP and ideal naming conventions for functions and variables. In both situations, I have the bulk of the writing already completed and just need to polish it up and get it into a blog article.

No Comments