I need to replace null value to 0 and change original arrays to output. My code are not work… Only change the second foreach loop value. how to do it? I need the output array is… (My null value is not fixed in key) thank you very much… my array:
Array ( [0] => Array ( [D1] => 2 [D2] => 2 [D3] => (Expect the null value to change to 0) [D4] => (Expect the null value to change to 0) [D6] => (Expect the null value to change to 0) [N1] => 1 [N2] => 1 [N3] => (Expect the null value to change to 0) [N4] => (Expect the null value to change to 0) [N5] => (Expect the null value to change to 0) ) [1] => Array ( [D1] => 3 [D2] => 2 [D3] => 2 [D4] => 2 [D5] => (Expect the null value to change to 0) [D6] => (Expect the null value to change to 0) [T1] => 1 [T2] => 1 [T3] => -1 [T4] => (Expect the null value to change to 0) [T5] => (Expect the null value to change to 0) ) )
Below is my code:
foreach($myArray as $key=> $value){ foreach($value as $key2 => $value2){ if(empty($value[$key2])){ $value[$key2]="0"; } //print_R($value[$key2]); }
Advertisement
Answer
You can use &
which passes variable reference in the foreach loop.
You can try the below codes.
foreach ($myArray as $key => &$value) { foreach ($value as $key2 => $value2) { if($value2 == null) { $value[$key2]="0"; } } } print_r($myArray);