Why in PHP is the expression "2 + '6 apples'' equal to 8?

51

I found the example to be funny, but the question is valid in understanding why PHP behaves this way.

When we make the sum shown below (an integer added to a string):

$numero_macas = 2 + '6 maçãs';

The result is:

8

But in this case, it only returns 2 :

2 + 'seis(6) maçãs'

Why does the PHP interpreter behave this way?

    
asked by anonymous 14.08.2015 / 14:37

4 answers

60

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'
    
14.08.2015 / 14:41
21

Because PHP tries to coerce type into operations of different types.

When he tries to convert the first one, he finds a number in the text and can convert it to a number, after he finds characters that are not numbers (or a valid numeric symbol in the position), he discards everything else.

In the second case it already finds invalid face characters and discards everything, with the number found in the text being 0 .

Ideally, you should not rely on string data for automatic conversion. It is best to validate before doing the operation.

    
14.08.2015 / 14:41
6

The interpreter automatically converts string started by 6 into number 6.66 and '66' and '66 abacates' will all be interpreted in the numerical statement as 66.     

14.08.2015 / 14:41
4

This is because PHP creates an automatic cast fault of the string for int or float

Let's look at this example:

echo (float) '120.5 por cento de aumento da conta de luz';

Result

120.5
    
14.08.2015 / 14:45