note 80839 added to ref.array

From: Date: Sat, 02 Feb 2008 21:12:42 +0000
Subject: note 80839 added to ref.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-135739@lists.php.net to get a copy of this message
Here are two more functions handling string2array and access array by string. It's useful if you want to access an array in xpath-style, such as parse_ini_file return values with $process_sections = TRUE. <?php function createArrayByString($string, $separator, $value = NULL) { if (strlen($string) > 0) { $splitter = explode($separator, $string); $index = array_shift($splitter); // get first element $function = __FUNCTION__; return array($index => $function(implode($separator, $splitter), $separator, $value)); } return $value; } function accessArrayByString($array, $string, $separator, $default = NULL) { if (!is_array($array)) { return empty($string) ? $array : $default; } @list ($key, $rest) = explode($separator, $string, 2); // @ needed for last access $function = __FUNCTION__; return array_key_exists($key, $array) ? $function($array[$key], $rest, $separator, $default) : $default; } $string = "one.two.three.four"; $separator = "."; $array = createArrayByString($string, $separator, "standard value"); $return = accessArrayByString($array, $string, $separator, "element not found"); var_dump($array); // should return array("one" => array("two" => array("three" => array("four" => "standard value")))) var_dump($return); // should return "standard value"; ?> change the function name to what ever you want, the recursive call uses __FUNCTION__ for re-call. ---- Server IP: 217.13.201.10 Probable Submitter: 84.57.246.66 ---- Manual Page -- http://www.php.net/manual/en/ref.array.php Edit -- https://master.php.net/note/edit/80839 Del: integrated -- https://master.php.net/note/delete/80839/integrated Del: useless -- https://master.php.net/note/delete/80839/useless Del: bad code -- https://master.php.net/note/delete/80839/bad+code Del: spam -- https://master.php.net/note/delete/80839/spam Del: non-english -- https://master.php.net/note/delete/80839/non-english Del: in docs -- https://master.php.net/note/delete/80839/in+docs Del: other reasons-- https://master.php.net/note/delete/80839 Reject -- https://master.php.net/note/reject/80839 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#135739) next »