2

How to send an indexes name for php array vairable.

the array is

$array = array('Somthing'=>array('More'=>array('id'=> 34)));

and now I want to display this thing but with a variable name I don't know how to explain so I write what I want to have.

$index_name = '[Something][More][id]';

$array{$index_name};

Is it possible in any way ?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Galileox86
  • 550
  • 5
  • 10
  • This should be possible with regular expressions. But it wouldnt be very effective or flexible to change. – Tammo Jan 31 '10 at 14:26
  • BTW, you have a typo in your original code. You define a key in $array called 'Somthing' but then you try to reference it later calling it 'Something'. – AJ. Jan 31 '10 at 14:32
  • Don't miss valid answers to this question that make this very simple to do using eval(). It's important to discuss best practices on SO, but it's silly when we ignore valid and simple solutions to problems just because we assume we know the situation better than the OP. Cheers. – T. Brian Jones Sep 27 '12 at 20:10

5 Answers5

15

Not in one go like that. Here's how you'd do it:

$array['Something']['More']['id']

If you particularly wanted access multidimensional arrays with a single string, then you could build a function to do that:

function array_multi(Array $arr, $path) {
    $parts = explode(".", $path);

    $curr =& $arr;
    for ($i = 0, $l = count($parts); $i < $l; ++$i) {
        if (!isset($curr[$parts[$i]])) {
            // path doesn't exist
            return null;
        } else if (($i < $l - 1) && !is_array($curr[$parts[$i]]) {
            // path doesn't exist
            return null;
        }
        $curr =& $curr[$parts[$i]];
    }
    return $curr;
}

// usage:
echo array_multi($array, "Something.More.id");    // 34
echo array_multi($array, "Something.More");       // array("id" => 34)
nickf
  • 537,072
  • 198
  • 649
  • 721
2

Recursive version supporting your syntax with square brackets:

$array = array('Something'=>array('More'=>array('id'=> 34)));

$string = '[Something][More][id]';

echo scan_array($string, $array);

function scan_array($string, $array) {
    list($key, $rest) = preg_split('/[[\]]/', $string, 2, PREG_SPLIT_NO_EMPTY);
    if ( $key && $rest ) {
        return scan_array($rest, $array[$key]);
    } elseif ( $key ) {
        return $array[$key];
    } else {
        return FALSE;
    }
}
Matteo Riva
  • 24,728
  • 12
  • 72
  • 104
1

You could do this with eval():

<?php

$array = array('Somthing'=>array('More'=>array('id'=> 34)));
$index_name = "['Somthing']['More']['id']";

$stmt='echo $array'.$index_name.';';
eval($stmt);

?>

UPDATE:

It seems some SO users are uncomfortable with the idea of using eval(). I think it makes sense to read this thread which discusses the pros and cons before deciding whether to use this in your own code.

Community
  • 1
  • 1
AJ.
  • 27,586
  • 18
  • 84
  • 94
1

Ok, I know this is how people get shot. But c'mon, eval() is not always the wrong answer.

$array = array('Something'=>array('More'=>array('id'=> 34)));
$index_name = '[Something][More][id]';
eval('$val = $array'.$index_name.';'); // Wrap in a function or something
kb.
  • 1,955
  • 16
  • 22
  • this is a perfect example of why it's wrong. you've got a syntax error in your **string**. who the hell wants to debug code which is being generated on the fly? – nickf Jan 31 '10 at 15:13
  • that code runs without problem, so i don't know where the alleged syntax error is. if you however refer to the missing quotes on the index keys i agree it's ugly, but it's not wrong. php evaluates all undefined constants to their string values, and i simply cut'n'pasted from op. – kb. Jan 31 '10 at 15:18
1

If you've cornered yourself into needing to do something like this, there's a pretty good chance you've done something else in a poor way. There's valid reasons to do this, but not very often.

function key_path($arr, $keys) {
    return $keys ? key_path($arr[array_shift($keys)], $keys) : $arr;
}

$arr['Something']['More']['id'] = 34;
$keys = array('Something', 'More', 'id');

var_dump( key_path($arr, $keys));
goat
  • 31,486
  • 7
  • 73
  • 96