PHP 8.1 throws error Uncaught TypeError: Cannot access offset of type string on string

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?
Answer
Solution:
PHP 7.4 was just being kind to you in the past. Part of PHP8 is to do away with a lot auto fixing and other nonsense that indulged bad coding and vulnerabilities.
Re write what you have to :
$products = ["HospitalProductID" => 260, "HospitalProtocolID" => 82];
foreach ($products as $product => $id) {
}
$product
is your Item and$id
is your int.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.