PDA

View Full Version : (PHP) array_path



traq
05-21-2013, 05:30 AM
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 (https://gist.github.com/customanything/5617523) (most recent version)

<?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!"

*/