PHP Code

Get the value of an array element with PHP

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);
Share

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image