Helper Methods for Working with Arrays

Published on January 23rd, 2011

This post is just some quick functions that can help you in working with arrays. These are especially helpful when working with document oriented databases such as MongoDB where the schema may not always be consistent between data.

<h2>Array Element</h2>
<p>
    When working with nested arrays it helps to be able to dive into the data and provide a fallback if the element you
    want does not exist. It allows you to dive as far as you want into an array by using a dot notation.
</p>
<script src="https://gist.github.com/791999.js"></script>
<p>
    For example if you wanted to access address information inside of an array you might do the following.
</p>
<script src="https://gist.github.com/792006.js?file=gistfile1.php"></script>

<h2>Array Sort</h2>
<p>
    This function allows you to sort an array by the value of any of the array's subelements. It works in conjunction with
    the array_element() function above so you can sort deep within arrays.
</p>
<script src="https://gist.github.com/792004.js"></script>
<p>
    Here is the example of how you may use this sort function with nested arrays.
</p>

<script src="https://gist.github.com/792010.js?file=gistfile1.php"></script>

<p>
    Just so you know I have contributed both of these functions to
    <a href="http://fuelphp.com/docs/classes/arr.html" target="_blank">FuelPHP's array class</a>. If you have not heard of
    <a href="http://fuelphp.com" target="_blank">FuelPHP</a> I recommend it highly as it borrows some of the best ideas
    from CodeIgniter, Kohana, and Rails.

    Thats really it. Let me know what you think in the comments.