Packy Packy - 1 year ago 70
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 Source
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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download