In a way, yes. We can use variables to help us though.
Let’s go back to the line I gave you in the first post of this thread:
$total_per_company[$data->customer] = (isset($total_per_company[$data->customer])) ? $total_per_company[$data->customer] + $data->extra_charge : $data->extra_charge;
Or, if I break it back down out of the ternary format:
if(isset($total_per_company[$data->customer])) {
$total_per_company[$data->customer] = $total_per_company[$data->customer] + $data->extra_charge;
} else {
$total_per_company[$data->customer] = $data->extra_charge;
}
So here, we need to talk about trying to reference an array key that doesnt yet exist.
$total_per_company is an array. it will be an associative array (meaning the keys of the array are strings).
At the end, we might have $total_per_company['ABC']
, which holds the total for ABC Corp, $total_per_company['XYZ']
for XYZ Corp, etc.
But we don’t know ahead of time what company names exist. instead, what we do is, for each row in our data, we look at the $data[‘co’] name.
$total_per_company[$data[‘co’]] will be “the array entry for whatever company the current row is talking about.”
We dont know if there’s already an entry in our array for that company - the array starts empty, after all, so either this row is the first time we’ve encountered ABC Corp, or it’s not.
If it is NOT the first time we’ve seen ABC corp, we want to take our previous total, and add the new value.
If it IS the first time we’ve seen ABC corp, we create a new entry in the array for that corporation, and we can give it the value of the current row. Because 0+X is X.
So, we need to check if the entry exists already: isset($total_per_company[$data['co']])
(“Is the entry for this row’s company set/does it exist”) will return true (it exists) or false (it doesnt).
Let me know if i’m losing you here.