Niklas Scherden
Niklas Scherden

Reputation: 115

Split a string into keys of associative arrays (PHP)

Do you have an idea, how can a string be converted to a variable, e.g.

I want to use all with explode(); exploded values to access the array $arr. I tried this code:

$c = explode('|', $string);
$str = 'arr[' . implode('][', $c) . ']';

echo $$str;

It doesnt work, sadly :( Any ideas?

Upvotes: 1

Views: 399

Answers (2)

Justin Iurman
Justin Iurman

Reputation: 19016

You're doing it wrong.
You can do what you want with a loop to go through the array level by level

$string = 'one|two|three';
$arr = array('one' => array('two' => array('three' => 'WELCOME')));

$c = explode('|', $string);
$result = $arr;

foreach($c as $key)
    $result = $result[$key];

echo $result; // WELCOME

Upvotes: 1

u_mulder
u_mulder

Reputation: 54841

Here's a sort of recursive function:

$ex_keys = array('one', 'two', 'three');
$ex_arr = array('one' => array('two' => array('three' => 'WELCOME')));

function get_recursive_var($keys, $arr) {
    if (sizeof($keys) == 1)
        return $arr[$keys[0]];
    else {
        $key = array_shift($keys);
        return get_recursive_var($keys, $arr[$key]);
    }
}

var_dump(get_recursive_var($ex_keys, $ex_arr));

Upvotes: 0

Related Questions