2

I have a string that contains elements from array.

$str = '[some][string]';
$array = array();

How can I get the value of $array['some']['string'] using $str?

1
  • 3
    I think what you're trying to do wouldn't be very good practice anyway. Better to do $array[$key1][$key2]. Commented Aug 8, 2011 at 11:10

4 Answers 4

4

This will work for any number of keys:

$keys = explode('][', substr($str, 1, -1));
$value = $array;
foreach($keys as $key)
    $value = $value[$key];

echo $value
Sign up to request clarification or add additional context in comments.

4 Comments

Actually, this is the best case.I won't remove the accepted from @hakre, but I gave you+.Thanks to all that have participated!
@Daniel: Care to elaborate?
@Eric No need for that :)
Gaah, @BobGregor edited it and broke it (replacing $array with array()
3

You can do so by using eval, don't know if your comfortable with it:

$array['some']['string'] = 'test';    
$str = '[some][string]';    
$code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));    
$value = eval($code);    
echo $value; # test

However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.

Another example if you need to write access to the array item, you can do the following:

$array['some']['string'] = 'test';
$str = '[some][string]';
$path = explode('][', substr($str, 1, -1));
$value = &$array;
foreach($path as $segment)
{
    $value = &$value[$segment];
}

echo $value;
$value = 'changed';
print_r($array);

This is actually the same principle as in Eric's answer but referencing the variable.

3 Comments

If he isn't comfortable with it, he shouldn't be storing the string that way.
@Eric: Don't know, but your solution looks much nicer :)
Its perfect.I've already tried with eval, but I didn't make it really well.
1
// trim the start and end brackets    
$str = trim($str, '[]');
// explode the keys into an array
$keys = explode('][', $str);
// reference the array using the stored keys
$value = $array[$keys[0][$keys[1]];

2 Comments

Hi, what about bigger arrays? Anyway thanks for the response!
Bigger arrays weren't part of the original question!
0

I think regexp should do the trick better:

$array['some']['string'] = 'test';
$str = '[some][string]';
if (preg_match('/\[(?<key1>\w+)\]\[(?<key2>\w+)\]/', $str, $keys))
{
    if (isset($array[$keys['key1']][$keys['key2']]))
         echo $array[$keys['key1']][$keys['key2']]; // do what you need
}

But I would think twice before dealing with arrays your way :D

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.