Get the value of an array element with PHP

by admin on July 24, 2009 · 0 comments

Using eval to get the value of an array element can be fairly resource expensive and inefficient. This handy little function will provide you with a quick alternative when you only know the coordinates and don't want to use eval().

Just remember, the object $coordinates should be an array with each value containing the next key to the needed value.

And obviously, $array is the array you wish to get the value from.

function get_in_array($coordinates, $array) {
     if(!is_array($coordinates)) {
          return FALSE;
     }
     
     if(!is_array($array)) {
          return FALSE;
     }
         
     foreach($coordinates as $val) {
          if(!isset($array[$val])) {
               return FALSE;
          }
          $array = $array[$val];
     }
 
     return $array;
}
 
//Example:
$array = array(range(1,10), array(range('a', 'e')));
echo get_in_array(array(1,0,3), $array);

Previous post:

Next post: