'How can we change this PHP function to work with PHP 8? [duplicate]

Would anyone know how we can rewrite the following function to be compatible and work with PHP 8?

function wpsc_have_shipping_quote() {

    $has_quote = false;

    global $wpsc_cart;

    if ( $wpsc_cart->shipping_quote_count > 0 || count( $wpsc_cart->shipping_quotes ) > 0 ) {
        $has_quote = true;
    }

    return $has_quote;
}


Solution 1:[1]

Andy. Kind regards.

In PHP 8.+, count() does not accept null values anymore, it was already throwing warnings since PHP 7.2 if I recall correctly. Therefore the code is failing exactly here:

count( $wpsc_cart->shipping_quotes ) > 0

because in some situations $wpsc_cart->shipping_quotes may be null (it was not set).

You can use the new PHP 8 null coalescing to check if the value is null, and if it is null, you can provide an empty array []. So change the line:

if ( $wpsc_cart->shipping_quote_count > 0 || count( $wpsc_cart->shipping_quotes ) > 0 ) {

To:

if ( $wpsc_cart->shipping_quote_count > 0 || count( $wpsc_cart->shipping_quotes ?? [] ) > 0 ) {

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1