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

Viewed 2472

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;
        }
    }
1 Answers

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.

UPDATE:

Since you have confirmed you are using MYSQLI, you should be using MYSQLI fetch functions like :

fetch_object() Returns your results as an Object.

if ( $products = $mysqli->query( $sql ) ) {
    while ( $product = $products->fetch_object() ) {
        $product->HospitalProductID;

    }
}
$products->close();

fetch_assoc() Returns your results as an Associative Array.

if ( $products = $mysqli->query( $sql ) ) {
    while ( $product = $products->fetch_assoc() ) {
        $product['HospitalProductID'];

    }
}
$products->close();

Here is a list of all possible methods you can use with the result class: https://www.php.net/manual/en/class.mysqli-result.php

I would also implore you to check out Prepared Statements. Especially if you are allowing any type of input from out with the hardcoding of the script: https://www.php.net/manual/en/mysqli-stmt.get-result.php

Related