Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fatal error: Uncaught TypeError: Unsupported operand types: int + string on PHP 8.0.8 [duplicate]

Tags:

php

php-8

Im converting number format like 35,578,926 to short word like 35.5M (or million). My code works fine on PHP 7.4, on the latest version 8.0.8 the fatal error occurs.

function convert($n)
{
    $n = (0 + str_replace(",", "", $n));
    if (!is_numeric($n)) return false;
    if ($n > 1000000000000) return round(($n / 1000000000000) , 1) . 'T';
    else if ($n > 1000000000) return round(($n / 1000000000) , 1) . 'B';
    else if ($n > 1000000) return round(($n / 1000000) , 1) . 'M';
    else if ($n > 1000) return round(($n / 1000) , 1) . 'K';
    return number_format($n);
}
$n = '35578926';

On PHP 7.4 this code returns the output:

$n = convert('35578926'); 
echo $n; // 35.5M

I tried changing

$n = (0 . str_replace(",", "", $n)); // this resolve nothing but no error 


$n = null; // also this resolve nothing but no error

So how do i convert this number (35578926 or 35,578,926) into short word like 35.5M on PHP 8.0.8?

like image 778
Wan Ahmad Aiman Avatar asked Oct 19 '25 19:10

Wan Ahmad Aiman


1 Answers

I suspect this line of code was written by someone more familiar with JavaScript (or some other language) than PHP:

$n = (0 + str_replace(",", "", $n));

In JavaScript, the "0 +" here is an idiomatic way of forcing a value to be a "number" rather than a string. However, in PHP, there are explicit cast operators for that purpose, as well as separate integer and floating-point types, so the line should be either:

$n = (int)str_replace(",", "", $n);

or:

$n = (float)str_replace(",", "", $n);

There is also another bug here, which is that this line happens too late:

if (!is_numeric($n)) return false;

Currently, this is run after converting the string into a number, so it is impossible for it not to be numeric. This would make more sense:

$n = str_replace(",", "", $n);
if (!is_numeric($n)) return false;
$n = (float)$n;

Note that is_numeric has a very broad definition of "numeric", so if you actually just want integers, you probably want ctype_digit instead:

$n = str_replace(",", "", $n);
if (!ctype_digit($n)) return false;
$n = (int)$n;
like image 59
IMSoP Avatar answered Oct 22 '25 10:10

IMSoP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!