note 112905 added to language.variables.variable
| From: | cgray at metamedia dot us | Date: | Mon, 05 Aug 2013 14:14:57 +0000 |
| Subject: | note 112905 added to language.variables.variable | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-195872@lists.php.net to get a copy of this message | ||
Returning values from a multidimensional array based using variable variables
and infinite key depth
I banged my head against this but could not find a way in language structure or
in functions to retreive a value from a multidimensional array where the key
path is known as a variable string. I considered some sort of recursive
function, but it seemed cumbersome for what should be a one-liner.
My solution uses eval() to return the array value:
<?php
$geolocation = array("ip"=>"127.0.0.1", "location" =>
array("city" =>
"Knoxville", "state_province" => "TN", "country" =>
"USA"));
print_r($geolocation); // Array ( [ip] => 127.0.0.1 [location] => Array ( [city]
=> Knoxville [state_province] => TN [country] => USA ) )
// typical use of variable variables
$key = "ip";
$result = $geolocation[$key];
print_r($result); // 127.0.0.1
$key = "location"; // another typical use of variable variables
$result = $geolocation[$key];
print_r($result); // Array ( [city] => Knoxville [state_province] => TN
[country] => USA )
// but how do we go deeper? this does NOT work
$key = "location['city']";
// $result = $geolocation[$key]; // Notice: Undefined index: location['city']
// print_r($result);
// this does NOT work
$key = "['location']['city']";
// $result = $geolocation{$key}; // Notice: Undefined index: ['location']
['city']
// print_r($result);
// this works:
$key = "['location']['city']";
$result = eval('echo $geolocation'."$key;");
print_r($result); // Knoxville
?>
----
Server IP: 69.147.83.199
Probable Submitter: 194.74.98.34
----
Manual Page -- http://php.net/manual/en/language.variables.variable.php
Edit -- https://master.php.net/note/edit/112905
Del: integrated -- https://master.php.net/note/delete/112905/integrated
Del: useless -- https://master.php.net/note/delete/112905/useless
Del: bad code -- https://master.php.net/note/delete/112905/bad+code
Del: spam -- https://master.php.net/note/delete/112905/spam
Del: non-english -- https://master.php.net/note/delete/112905/non-english
Del: in docs -- https://master.php.net/note/delete/112905/in+docs
Del: other reasons-- https://master.php.net/note/delete/112905
Reject -- https://master.php.net/note/reject/112905
Search -- https://master.php.net/manage/user-notes.php