Reputation: 379
I have a recursive array depth of which is variable, and I want to be able to take a string with a separator and convert that string to an index in that array,
For example
$path = 'level1.level2.level3';
will be converted to get the value 'my data' from the array below
$data['level1']['level2']['level3'] = 'my data';
I thought the quickest way to get this would be to use variable variables, but when I try the following code
$index = "data['level1']['level2']['level3']";
echo $$index;
I get the follwing error
PHP Notice: Undefined variable: data['level1']['level2']['level3']
All other ways I can think of doing this are very inefficient, could someone please shed some light on this, is it possible using variable variables for arrays in PHP? Any other efficient workaround?
Many thanks.
Upvotes: 0
Views: 158
Reputation: 88697
It is a tricky one this, here is the most efficient way I can think of:
function get_value_from_array ($array, $path, $pathSep = '.') {
foreach (explode($pathSep, $path) as $pathPart) {
if (isset($array[$pathPart])) {
$array = $array[$pathPart];
} else {
return FALSE;
}
}
return $array;
}
Returns the value, or FALSE on failure.
Upvotes: 2
Reputation: 57326
You can use eval
function like so:
$data['level1']['level2']['level3'] = 'my data';
eval("\$index = \$data['level1']['level2']['level3'];");
echo $index;
Upvotes: -1
Reputation: 6570
Something like this:
eval('$data[\''.implode("']['",explode('.',$path))."'] = 'my data';");
...but don't ever, ever tell anyone I told you to do this.
Upvotes: -1
Reputation: 18859
You'll have to loop the array, you won't manage to do this using variable variables, as far as I know. This seems to work though:
<?php
function retrieve( $array, $path ) {
$current = $array;
foreach( explode( '.', $path ) as $segment ) {
if( false === array_key_exists( $segment, $current ) ) {
return false;
}
$current = $current[$segment];
}
return $current;
}
$path = 'level1.level2.level3';
// will be converted to get the value 'my data' from the array below
$data['level1']['level2']['level3'] = 'my data';
var_dump( retrieve( $data, $path ) );
Upvotes: 2
Reputation: 50974
Try
$index = "data";
echo $$index['level1']['level2']['level3'];
instead, because $index
should be only variable name
Upvotes: 0