0

I have the 'path' to an array value stored in a variable, and I am trying to set the value. What I am trying to do is this:

$array['Breaks'][1]['In'] = "XXX";

However, I have ['Breaks'][1]['In'] stored in a variable. So I am essentially trying to do something like this:

$path = "['Breaks'][1]['In']";
$array.$path = "XXX";

This doesn't work though, and I'm not exactly sure how to go about making this work correctly.

Any suggestions?

8
  • You could try to parse $path and then cycle through the parsed values to set the value. Commented Nov 2, 2012 at 20:24
  • Why do you have ['Breaks'][1]['In'] in a variable? Related: meta.stackexchange.com/questions/66377/what-is-the-xy-problem Commented Nov 2, 2012 at 20:26
  • I am using AJAX to dynamically update values in a large array. It POSTs the data, and this is POSTed to my update script to be able to select and modify the data. Commented Nov 2, 2012 at 20:28
  • Uhhu. And why do you have ['Breaks'][1]['In'] in a variable again? Commented Nov 2, 2012 at 20:30
  • ... so my script can update that value? Commented Nov 2, 2012 at 20:31

3 Answers 3

2

As long as the path string is not modifiable by users or parsed through previously you could just do:

eval("\$array".$path." = 'Value';");
Sign up to request clarification or add additional context in comments.

Comments

1

Try doing this,

//This solution works if you are sure the length of $path_arr is going to be 3
$path = "['Breaks'][1]['In']";
$path_arr = explode(']', str_replace(array("['", "'", "["), '', $path)); 

$array[$path_arr[0]][$path_arr[1]][$path_arr[2]] = "XXX";
var_dump($array);

Demo

1 Comment

Thank you! Simple, and works, just as I asked. Appreciate it.
1

Try extracting each component of the $path variable into its own variable, or into an array ($pathArray below). So, if you had $pathArray[0] set to 'Breaks', $pathArray[1] set to 1, etc., you could do something like:

$array[$pathArray[0]][$[pathArray[1]][$[pathArray[2]] = "XXX";

Although this seems like an unusual way to go about things, and it might be worth re-thinking your approach entirely.

Comments

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.