Results 1 to 1 of 1

Thread: (PHP) array_path

  1. #1
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 516 Times in 502 Posts
    Blog Entries
    5

    Default (PHP) array_path

    a useful PHP snippet. enjoy

    Given a list of index keys (a path) and a subject array, checks if the path exists in the array and returns the end value if so.

    Limitation: cannot distinguish between a path that does not exist and a final value of null.
    You could throw an error/exception if this might ever be necessary (but it probably won't).

    View on Github (most recent version)
    PHP Code:
    <?php
    /**
     * allows dynamic access to multi-dimensional arrays
     * (using a sequence of values as index keys).
     *
     * @author     Adrian Testa-Avila <github@custom-anything.com>
     * @copyright  2013 Adrian Testa-Avila
     * @license    creative commons attribution-sharealike
     *             http://creativecommons.org/licenses/by-sa/3.0/
     *
     * @param array $path     list of index keys (index path to follow)
     * @param array $array    subject array
     * @return mixed          the value at $array[$path] if set; 
     *                        null otherwise
     */
     
    function array_path( array $path,array $array ){
        foreach( 
    $path as $index ){
            if( isset( 
    $array[$index] ) ){
                
    $array $array[$index];
            }
            else{
                return 
    null;
            }
        }
        return 
    $array;
    }
     
    ##         EXAMPLE USAGE         ##
    ##       uncomment to test       ##
    /*
     
    $a = array(
      'one' => array(
        'two' => array(
          'three' => 'found me!'
        )
      )
    );
     
    print array_path( array('one','two','three'),$a );
    // prints "found me!"
     
    */
    Last edited by traq; 05-21-2013 at 06:35 AM.

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •