There is an array:

$myArray = [ 0 => [ id => 1, title => 'title1' ], 1 => [ id => 2, title => 'title2' ], 2 => [ id => 3, title => 'title3' ], 3 => [ id => 4, title => 'title4' ] ]; 

Now there is a function in which I transfer the value of the array and the resulting value from the function needs to be written to the same array.

How to do this through foreach, when iterating through an array, add a new value to the array?

 foreach ($myArray as $item) { $item[]['funcResult'] = myFunc($item['id']); } 

If we write it like this, we get an array:

 $myArray = [ 0 => [ id => 1, title => 'title1' ], 1 => [ id => 2, title => 'title2' ], 2 => [ id => 3, title => 'title3' ], 3 => [ id => 4, title => 'title4' ] 4 => ['funcResult' => '5'], ]; 

And you need to add all elements, such as:

 $myArray = [ 0 => [ id => 1, title => 'title1', 'funcResult' => '2' ], 1 => [ id => 2, title => 'title2', 'funcResult' => '3' ], 2 => [ id => 3, title => 'title3', 'funcResult' => '1' ], 3 => [ id => 4, title => 'title4', 'funcResult' => '5' ] ]; 

Solved the problem through for, but is there an option through foreach?

    4 answers 4

    The code of the function myfunc () is not given, therefore:

     foreach ($myArray as $key => $item) { $myArray[$key]['funcResult'] = $item['id']; } unset($key); 

    Result:

     Array ( [0] => Array ( [id] => 1 [title] => title1 [funcResult] => 1 ) [1] => Array ( [id] => 2 [title] => title2 [funcResult] => 2 ) [2] => Array ( [id] => 3 [title] => title3 [funcResult] => 3 ) [3] => Array ( [id] => 4 [title] => title4 [funcResult] => 4 ) ) 

    You can pass the value by reference with "&":

     foreach($array as &$item){ $item['any'] = true; } 
    • You repeated my answer , with abbreviations? =) - Sergiks
    • @Sergiks, did not notice your answer) - D.Nazarenko
     foreach ($myArray as $key => $item) { $myArray[$key]['funcResult'] = myFunc($item['id']); } 

      You can transfer the next element by the link , and change it:

       foreach( $myArray as &$item) { $item['funcResult'] = myFunc( $item['id']); } unset( $item); 

      A working example where in id value of id is multiplied by 10.

      Result:

       Array ( [0] => Array ( [id] => 1 [title] => title1 [funcResult] => 10 ) [1] => Array ( [id] => 2 [title] => title2 [funcResult] => 20 ) [2] => Array ( [id] => 3 [title] => title3 [funcResult] => 30 ) [3] => Array ( [id] => 4 [title] => title4 [funcResult] => 40 ) )