2

After updating to PHP 7.3 I get the following error

PHP Warning: A non-numeric value encountered in /functions.php on line 3702

Line 3702:

$total += $rating['rating_score'];

Function code:

function airkit_get_rating( $post_id ) {

if ( is_numeric($post_id) ) {
    $rating_items = get_post_meta($post_id, 'ts_post_rating', TRUE);
    if ( isset($rating_items) && is_array($rating_items) && !empty($rating_items) ) {
        $total = '';
        foreach($rating_items as $rating) {
            $total += $rating['rating_score'];
        }
        if ( $total > 0 ) {
            $round = intval($total) / count($rating_items);
            $result = round($round, 1);

            if ( is_int($round) ) {
                if ( $round == 10 ) return $result;
                else return $result . '.0';
            } else {
                return $result;
            }
        } else {
            return;
        }
    }
} else {
    return;
}}

I have no experience in PHP. Can anyone help me to correct this error?

3
  • 1
    You should initialize $total to 0, not ''. Commented Aug 30, 2019 at 22:38
  • You're trying to add a string and a number. It will automatically convert the string to a number, but now it generates a warning. Commented Aug 30, 2019 at 22:38
  • Actually, this isn't a new warning, I reproduced it in PHP 5. The upgrade probably changed your default error reporting level. Commented Aug 30, 2019 at 22:39

1 Answer 1

4

Change

$total = '';

to

$total = 0;

You're trying to add a number to a string, but the string doesn't look like a number. The empty string is converted to the number 0, so you get the correct total, but it also produces a warning.

Sign up to request clarification or add additional context in comments.

3 Comments

This seems to solve the issue. But I noticed that the same error can still be triggered if $rating['rating_score'] is also a string.
True, but why would that be a string?
If you're trying to concatenate strings you use ., not +.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.