What makes the expression "'2 pigs' + '3 horses' == '5 animals'" return true in PHP?

Asked

Viewed 218 times

-2

I’ve asked a similar question here at Stackoverlow at: Why in PHP the expression "2 + '6 apples'" is 8?

However, taking a look at some strange things curiosities that exist in PHP, I saw that the following expression returns true.

var_dump('2 porcos' + '3 cavalos' == '5 animais'); // bool(true)

I even agree that in PHP, the expression "2 porcos" + "3 cavalos" will return int(5), on account of the conversion of the initial numeric strings to the type int.

But why does comparison return true, since the content is completely different?

It is certain that == compares only the values, but we clearly see that the values are not equal.

I agree that the example below is correct:

var_dump('2 porcos' +  '3 cavalos' == 5); // bool(true)

However, this expression would not have to return false?

var_dump(5 == '5 animais'); // bool(true)

And even more questionable:

var_dump(5 == '00005 animais'); // bool(true);

Of course, when we do the conversion, "00005 animais" returns 5, but why is this valid in terms of comparison? This is bad.

I also noticed that in php 5 == '5 cãezinhos' returns true.

And this can be a problem for those who do not know these "curiosities" of language.

See some examples below

5 == '5 cavalos'; // true
'5' == '5 cavalos'; false
'5' == 5; // true
'5 ' == 5; // true
' 5' == 5; // true

Questions:

  • PHP at all times converts the values and then compares them?
  • When can I trust the comparison operation (==) and when I can rely only on the operator of identical (===)?
  • I do not know the principle used for comparison in PHP, maybe it is due to the fact of the initial purpose of the language. But, there goes the confusion even more in the explanation -> http://php.net/manual/en/types.comparisons.php What I do is always use === to be sure.

  • 1

    '5 ' == 5 // true

  • The answers to the previous question have already been sufficiently enlightening, if you want to take into account the type use ===

  • var_dump('5 ' == 5); of false?

  • 4

    @Wallacemaxters operators are not the same thing, but the answer is the same. The question is not the operators but how PHP works with the data.

3 answers

4


PHP always casts the values for booleans by default, so in some instructions where you believe you are comparing numbers for example, PHP is comparing booleans. Two important things are the order of the expressions and the comparison operator.

In the examples of the question it was used only of equal(==) it compares only values and discards type(int, bool, string etc).

5 == '5 cavalos'; comparação entre ints
'5' == '5 cavalos'; false pq é uma comparação entre strings
'5' == 5; // true, comparação entre ints 
'5 ' == 5; // true, mesma coisa

== should be used when only the import value idependente of type. === should be using when the value and variable type imported.

<?php
//O PHP entende isso como comparação entre booleanos, logo imprime 1(true)
//    1     ==   1
if((bool)-1 == 100){
    echo true;
}else{
    echo false;
}

//Comparação entre um bool e int, retorna 0(false) pois os tipos não os mesmos
//    1      ===  1      
if((bool)100 === 100){
    echo true;
}else{
    echo (int)false;
}
//Comparação entre o mesmo valor e tipo, logo é true
// 100 === 100
if(100 === 100){
    echo true;
}else{
    echo (int)false;
}

Exit: 101

Obs: I used echo (int)false; to print zero in the examples, without the cast, print nothing.

  • And in the case of ' 5' == 5? That’s weird

  • @Wallacemaxters It’s weird to be true?

  • Yeah, it would be a great discussion if it wasn’t closed. But do what doesn’t? Maybe nobody even opened the console to test :)

  • returns true yes @rray

  • @Wallacemaxters, see if this code will give a false and the other true. echo var_dump(' 5' == 5);&#xA;echo '<br>';&#xA;echo var_dump(' 5' == 5); lol vc need to copy.

  • They both gave true. Like I said, @rray

  • I remember once q saw a certification issue q made a comparison with == and had the expressions in a specific order :P would give a bombastic result ... if I could find ... would give to exemplify well when the order of the cast and the comparison make a difference. @Wallacemaxters

  • @Wallacemaxters, I think he misconverted the first example, does the following remove the space, in place do, hold the altand tighten 255 and turn again hehe.

Show 3 more comments

3

var_dump(5 == '5 animais'); // bool(true)
E mais questionável ainda:

var_dump(5 == '00005 animais'); // bool(true);

Why would this return false? This has to do with the PHP mechanisms it "searches" the values that allow to make this calculation. And this is why PHP is a bad language because it allows most errors just displayed warnings. It is a sloppy language... As if($x = 5) becomes true because x assumes the value of 5. Often small promenores like these become bugs, PHP is sloppy and allows a lot of things that shouldn’t.

If you start programming in C++ tomorrow you’ll see what happens.

To return to the subject, given that 00005 is equivalent to 5 anywhere in the world, it is more than justifiable that this validation is true.

0 the left doesn’t count for anything, the right is already another conversation :)

If it were: var_dump(5 == '50000 animals') it would already have to give false.

I hope I’ve cleared something up. And remember, when it comes to PHP we have to be very careful because it’s very easy to slouch and we lose our good ways of programming.

A big hug.

EDIT:

For == and for ===.

== means equal.

=== that is to say strictly equal. That is, there is a minimum difference and the validation will already be false.

I use === when I receive parameters in my classes.

Example:

public function teste($table=false)
{
     if($table === false) return false;
}
  • In javascript this would return false: 5 == '5 pratas'. And yet you wonder why you would have to return false? The question really is: Why in PHP returns what other languages do not return?

  • 1

    I’ll say it again. PHP is a sloppy language. He will always try to show you a result, false or true, he will always try to achieve a result. Javascript does not do this. In fact, as soon as it detects an error, whatever, for the javascript execution and often for the whole page.

  • 1

    Thank you for your @Wilson placement. Although some people think it’s an opinion (and although I really like PHP), I agree that it is sloppy in some (I mean many) points.

  • Well, I’m glad I was helpful. I’ll walk around here. Hug

  • the interesting thing is that the Manual for PHP draws the comparison with == of Loose comparisons with ==

  • It is normal, because here we return to what I said. Strictly the same, that is, it has to be the same case otherwise it will be false. But yes, no doubt that the best thing to do is to read the documentation and thus learn a lot :)

  • <?php&#xA;$n = 25;&#xA;$n1 = 031;&#xA;if($n === $n1) echo true; pq that code of true :P hehe. + 1 for the answer.

Show 2 more comments

2

var_dump('2 porcos' + '3 cavalos' == '5 animais'); // bool(true)

When we add a number with a string in PHP, it tries to convert the string into a number and then adds the 2 as Concatenation and Mathematical Operations.

And according to Operators of Comparison,

If you compare an integer to a string, the string is converted to a number.

Therefore, when executing '2 porcos' + '3 cavalos' == '5 animais' the result is 2+3 == 5 5==5 true

  • I converted? Or did PHP convert? I just wanted to know if 5 == '00005 cavalos'!

  • PHP converted! I’m saying that in your question Voce forgot to convert the '5 animals' to 5...

  • to compare the values it converts the 2 expressions to the same type... as 5 is integer.. it tries to convert 0005 horses to integer.. that of the 5 also

  • I "haven’t forgotten". actually the question is exactly about that. It’s not a problem I’m facing or a question. I want to know why this happens. '3 chickens' + '3 ducks' == '6 birds' is correct. But I’m asking PHP to compare and not to convert anything. I want to know what the comparison is.

  • ok I will edit here based on searches

Browser other questions tagged

You are not signed in. Login or sign up in order to post.