-1

I created multiple dimensional array and tried to update count value for certain condition as below but not working.

$test[] = [
           'firstNm' => 'luke'
           ,'lastNm' => 'Lee'
           ,'count' => 10

         ];

$test[] = [
           'firstNm' => 'John'
           ,'lastNm' => 'Doe'
           ,'count' => 20
          ];

    foreach ($test as $test01)
    {
     if ($test01['firstNm'] === 'John'){
      $test01['count'] += 70 ;}
    }

Looking forward to your help. Thank you.

Luke Lee
  • 149
  • 1
  • 7

2 Answers2

1

Actually you are increasing the value but missing to reasign to the same array. Try this one.

   $test[] = [
           'firstNm' => 'luke'
           ,'lastNm' => 'Lee'
           ,'count' => 10

         ];

$test[] = [
           'firstNm' => 'John'
           ,'lastNm' => 'Doe'
           ,'count' => 20
          ];

    foreach ($test as $key => $test01)
    { 
     if ($test01['firstNm'] === 'John'){
       $test[$key]['count'] += 70 ;
      }
    }

print_r($test);    
Naga
  • 2,190
  • 3
  • 16
  • 21
0

Borrowing from this answer, which cites the PHP manual page for foreach:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.1

So you could iterate over the array elements by-reference:

foreach ($test as &$test01)
{
    if ($test01['firstNm'] === 'John'){
        $test01['count'] += 70 ;
    }
}

See this illustrated on Teh Playground.

Otherwise you can iterate using the key=>value syntax:

foreach ($test as $index=>$test01)
{
     if ($test01['firstNm'] === 'John'){
         $test[$index]['count'] += 70 ;
     }
}
Community
  • 1
  • 1
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58