The PHP interpretation mechanism works as follows, if the first part of the string is a valid number it is converted ( int
or float
) and the rest is discarded, except for some exceptions like the plus sign ( +
), minus ( -
), point ( .
) and notations, scientific ( e
) and hexadecimal ( x
), seems to follow the same pattern as filter_sanitize for numbers.
In the first example, after 6
everything is not considered a valid number.
$numero_macas = 2 + '6 maçãs';
^
|
a partir daqui acabou o número
Curious examples:
<?php
//10 em notação cientifica, resultado 12
echo 2 + '10eNaN abacaxis'. PHP_EOL;
//26 em notação hexadecimal, resultado 28
echo 2 + '0x1A abacaxis'. PHP_EOL;
//sinal de menos, resultado -1
echo 2 + '-3 abacaxis'. PHP_EOL;
//sinal de mais, resultado -2
echo -5 + '+3 abacaxis'. PHP_EOL;
//sinal de menos com ponto, resultado 4.9
echo 5 + '-.1 abacaxis'. PHP_EOL;
//sinal de mais seguido de ponto, resultado -4.9
echo -5 + '+.1 abacaxis'. PHP_EOL;
//sinal de ponto, resultado 3.1
echo 3 + '.1 abacaxis'. PHP_EOL;
Example - ideone
In some cases a number followed by a letter may be a valid number such as scientific notation, this is an issue very interesting on the subject.
If the string starts with a non-numeric value, it will not be converted.
2 + 'seis(6) maçãs'