|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2013-08-02 14:57 UTC] cgray at metamedia dot us
Description: ------------ Attempted to post a note multiple times to page: http://php.net/manual/en/language.variables.variable.php but always fail spam test. Bottom of page: "This mirror generously provided by: Yahoo! Inc." I would like to contribute and payback help I have found via article notes by others. PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Nov 20 04:00:01 2025 UTC |
Yes, you understanding of the report is correct. Using my email address @metamedia.us Below is what I was attempting to post. thanks -c! ----- 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 ?>