Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 ?

share|improve this question
 
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
add comment

5 Answers

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)
share|improve this answer
 
+1 I really like this answer :) –  Jacob Relkin Jan 31 '10 at 14:26
add comment

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;
    }
}
share|improve this answer
add comment

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
share|improve this answer
 
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
add comment

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.

share|improve this answer
2  
If you're going to take the time to downvote my answer, a comment would sure be nice. –  AJ. Jan 31 '10 at 14:37
1  
I would assume it has to do with eval() usage. I wasn't the one to downvote though. –  Daniel Sloof Jan 31 '10 at 14:39
2  
And specifically, what about eval() usage? It accomplishes what the OP wants to do. –  AJ. Jan 31 '10 at 14:41
add comment

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));
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.