1

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

  • there is a string -> $string = 'one|two|three';
  • there is an array -> $arr = array('one' => array('two' => array('three' => 'WELCOME')));

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?

3

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.