Wan Ahmad Aiman
Wan Ahmad Aiman

Reputation: 71

Fatal error: Uncaught TypeError: Unsupported operand types: int + string on PHP 8.0.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?

Upvotes: 3

Views: 16025

Answers (1)

IMSoP
IMSoP

Reputation: 97688

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;

Upvotes: 3

Related Questions