I am checking all my code in readiness for upgrading to PHP 8.1.
The following lines of code work fine in PHP7.4 but throws the above error on the line starting with "$pcount" in PHP 8.1
foreach ($products as $product) {
$pcount[$product['HospitalProductID']] += 1;
}
The $product array looks like this:
(
[HospitalProductID] => 260
[HospitalProtocolID] => 82
)
Any idea why PHP 8.1 does not like this code?
UPDATE I believe I found the cause of this issue and posting it here un case it might help others in the future.
The error is caused by the use of the += operator in conjunction with an array key that does not yet exist, therefore trying to add 1 to an undefined value.
I changed my code as follows and I no longer get the error.
foreach ($products as $product) {
if (isset($pcount[$product['HospitalProductID']])) {
$pcount[$product['HospitalProductID']] += 1;
} else {
$pcount[$product['HospitalProductID']] = 1;
}
}