0

I have found several purported solutions to this question, but when I try and implement them, they do not work.

$a = array('val'=>10, 'name'=>'Name of A', 'item3'=>'item3forA');
$b = array('val'=>20, 'name'=>'Name of B', 'item3'=>'item3forB');
$c = array('val'=>30, 'name'=>'Name of C', 'item3'=>'item3forC');
$d = array('val'=>40, 'name'=>'Name of D', 'item3'=>'item3forD');
$rlist = array($a, $b, $c, $d);

I need a way to recursively / iteratively replace the value of the 'val' key to make them all a zero (0) value.

Two of the many solutions I have tried are here and here. I will also note if I 'explicitly' set the key to zero $a['val']=0; $b['val']=0; etc., that works, but I would rather set it to zero with less code (the actual program has like 20 multi-dimensional arrays to modify).

2
  • 1
    Just loop and assign. Make sure you edit the same copy of the subarray. Commented Oct 22, 2020 at 13:58
  • Can you share more details? What have you tried so far? Where are you stuck? Commented Oct 22, 2020 at 14:04

2 Answers 2

1

PHP does assignment by value unless explicitly instructed otherwise, so when you do

$rlist = array($a, $b, $c, $d);

The inner arrays of $rlist will be the values of $a, $b, $c, and $d, not references to those actual variables. So if you're iterating over $rlist and modifying its values, you will not see those changes reflected in the original $a, $b, etc. variables.

If you need that to happen, you can assign those variables to $rlist by reference as well as using a reference when you iterate $rlist as shown in the other answer.

$rlist = array(&$a, &$b, &$c, &$d);

Other possibilities you may consider based on how they fit in with the rest of your code are

  • assigning the values of $a, etc. directly to $rlist['a'], etc. at the point where you're currently defining them as individual variables
  • using stdClass objects (or instances of a class you define) instead of arrays, which will not need to be assigned by reference to $rlist
Sign up to request clarification or add additional context in comments.

1 Comment

That did it! Thank you so much! :) This $rlist modification, in conjunction with @JitendraYadav's foreach loop is the solution.
1

Use the reference of the given array and just set val = 0.

foreach($rlist as &$data){
  $data['val'] = 0;
}

3 Comments

This code is not working. I understand this code, and believe it should work, but it just doesn't. It should not matter if I am trying to do this within an 'if' statement, right?
I changed your question, you should define $a, $b, $c, $d first and then assign them to $rlist.
I understand your edit. Makes sense, and that is what I am doing. Thank you.

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.