2

Is it possible to do something like this in PHP?

$index1 = "[0][1][2]";
$index2 = "['cat']['cow']['dog']";

// I want this to be $myArray[0][1][2]
$myArray{$index1} = 'stuff';

// I want this to be $myArray['cat']['cow']['dog']
$myArray{$index2} = 'morestuff';

I've searched for a solution, but I don't think I know the keywords involved in figuring this out.

2
  • 1
    You could do this with eval() but I recommend against using it. Could we ask why you want to do this? There might be another way to accomplish what you want :) Commented Feb 24, 2012 at 15:46
  • I am writing a recursive function the alters different dimension of an array. If you pass, $array['cow'] into a function, I'm pretty sure you cannot access $array from that function (even if passed by reference) Commented Feb 24, 2012 at 15:48

5 Answers 5

4
eval('$myArray[0][1][2] = "stuff";');
eval('$myArray'.$index1.' = "stuff";');

But be careful when using eval and user input as it is vulnerable to code injection attacks.

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

8 Comments

gahh, is eval() the only solution?
You could also do it the dirty way and parse your $index string and then loop though the array levels. interested in this approach?
eval might not be the only solution, but it is the best one. eval is exactly what you are looking for. Please don't mindlessly ignore the best solution just because you've heard people say "eval is evil".
well eval is evil, I usually look for all possible solutions before using it!
Guys be cool. We are all friends here. Everybody is allowed to believe what they want. We don't discuss opinions, we discuss arguments.
|
3

Not directly. $myArray[$index] would evaluate to $myArray['[0][1][2]']. You would probably have to separate each dimension or write a little function to interpret the string:

function strIndexArray($arr, $indices, $offset = 0) {
     $lb = strpos($indices, '[', $offset);
     if ($lb === -1) {
         return $arr[$indices];
     }
     else {
         $rb = strpos($indices,']', $lb);
         $index = substr($indices, $lb, $rb - $lb);
         return strIndexArray($arr[$index], substr($indices, $rb+1));
     }
}

You can probably find some regular expression to more easily extract the indices which would lead to something like:

$indices = /*regex*/;
$value = '';
foreach($indices as $index) {
    $value = $array[$index];
}

To set a value in the array the following function could be used:

function setValue(&$arr, $indices, $value) {
    $lb = strpos($indices, '[');
    if ($lb === -1) {
        $arr = $value;
    }
    else {
        $rb = strpos($indices, ']', $lb);
        $index = substr($indices, $lb, $rb);
        setValue($arr[$index], substr($indices, $lb, $rb+1), $value);
    }
}

Note: I made above code in the answer editor so it may contain a typo or two ; )

5 Comments

I just realized my answer is not a solution as it's only to get a value and the question asker wants to set a value.
I'm trying to think of a regex solution, but what would happen if you come across `$index = "['[a]']";. I think the possible input for a general solution might be too complex for one.
In that case the thing would break and use the '[a as index, then again, it uses that index both for getting and setting so all is not lost. Besides that, I've never in my life used a [ or ] in an array index, but I can understand that's just me.
I picked this one, because it shows the coder clear intent of what the code is accomplishing. To anyone reading this, eval() could be an acceptable solution, but having a function call with the intent is much better in practice.
Re the ['[a]'], a check of $lb2 = strpos($indices,'[',$lb); $lb2 < $rb; could catch that special case.
1
$index1 = "[0][1][2]";
$index2 = "['cat']['cow']['dog']";

function myArrayFunc(&$myArray,$myIndex,$myData) {
    $myIndex = explode('][',trim($myIndex,'[]'));
    $m = &$myArray;
    foreach($myIndex as $myNode) {
        $myNode = trim($myNode,"'");
        $m[$myNode] = NULL;
        $m = &$m[$myNode];
    }
    $m = $myData;
}

// I want this to be $myArray[0][1][2]
myArrayFunc($myArray,$index1,'stuff');

// I want this to be $myArray['cat']['cow']['dog']
myArrayFunc($myArray,$index2,'morestuff');


var_dump($myArray);

Comments

0

There's always the evil eval:

eval('$myArray' . $index1 . ' = "stuff";');

Comments

-3

You can use two anonymous functions for this.

$getThatValue = function($array){ return $array[0][1][2]; };
$setThatValue = function(&$array, $val){ $array[0][1][2] = $val; };

$setThatValue($myArray, 'whatever');
$myValue = $getThatValue($myArray);

3 Comments

I understood the question to mean "[0][1][2]" was variable.
he wants it the other way around :)
What happens if the indexes change?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.