Packy Packy - 1 month ago 11
PHP Question

Add key and value to array if it doesnt exist

So I have an Array called $sales that consits of objects like:

"DR22" => array:3 [▼
"brand" => "DR22"
"year" => "0"
"last_year" => null
]
"FGIPA46C" => array:3 [▼
"brand" => "FGIPA46C"
"month" => "3"
"year" => "3"
]


Now each one should have "Month" "Year" "Last Year" "Last Month" but if there is no sale its not in there, which i get, but if it doesnt exist I just want to add it with 0 value. I tried:

foreach ($sales as $sale)
{
if (empty($sale['month'])) {
$sale['month'] = 0;
}
}


But it doesnt add anything. Spits out the same.

Answer
foreach ($sales as &$sale) {if (empty($sale['month']))        { $sale['month'] = 0; }}

You need to pass the $sale array by reference (using the &). This will mean that the original $sales array is updated

Comments