Wyatt Jackson
Wyatt Jackson

Reputation: 303

How do I fix my "PHP Warning: A non-numeric value encountered" error?

I have read through many other posts about this non-numeric value encountered error, but unfortunately, I may be dense. I'm not sure how to fix this annoying error.

Here is my code block:

 foreach ($local_words as $local_word_to_check){

                $letters = mb_str_split($local_word_to_check);
                $letters = array_map( 'addslashes', $letters );

                $local_total_letter_box_length = "";

                $query2 = "SELECT GROUP_CONCAT(Alpha) AS Alpha,
                                 GROUP_CONCAT(Letter_Box_Width) AS Letter_Box_Width
                          FROM Font_Krinkes
                          WHERE Alpha IN ('" . implode("','", $letters) . "')";

                $result2 = mysqli_query($con, $query2) or die("unable to query database!");

                if ($row = mysqli_fetch_assoc($result2)) {
                    $widths = array_combine(explode(',', $row['Alpha']), explode(',', $row['Letter_Box_Width']));
                    $total_word_box_width = 0;
                    foreach (mb_str_split($local_word_to_check) as $letter) {
                        $local_total_letter_box_length += $widths[$letter];
                    }
                }

                $complete_font_values[] = $local_total_letter_box_length;  

                unset($letters);
        }

The error happens on this line:

$local_total_letter_box_length += $widths[$letter];

Any help is very much appreciated.

Upvotes: 2

Views: 29765

Answers (3)

Mohsen
Mohsen

Reputation: 4235

Most of time, this error happens when used "+" as strings concatenation operator like other languages, but in PHP strings concatenation operator is ".", if you have numberic value as string you have to cast it like $num = (int) "10" + (int) "20";

Upvotes: 1

Ahmad Saad
Ahmad Saad

Reputation: 803

Use

$local_total_letter_box_length = 0; 

Instead of

$local_total_letter_box_length = "";

Upvotes: 2

mickmackusa
mickmackusa

Reputation: 48100

$local_total_letter_box_length = ""; is a string when it is first declared.

$local_total_letter_box_length += $widths[$letter]

That's not how you concatenate a string in php.

Use .= to concatenate.


If you mean to increase a numeric value, declare your variable with 0.

+= is okay to use on numeric values and arrays.

Code: (Demo)

$integer = 5;
$integer += 10;
echo $integer , "\n---\n";


$array = ['good' => 'one'];
$array += ['two'];
var_export($array);

Output:

15
---
array (
  'good' => 'one',
  0 => 'two',
)

Upvotes: 10

Related Questions