Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.6K
Visualizações
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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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;
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda