0

I came across this while playing with php

$test1 = '123abc';
$test2 = 123;

var_dump($test1); echo "<br />";
var_dump($test2); echo "<br />";

$test3 = ($test1 == $test2) ? True : False;
var_dump($test3);

This resulted in:

string(6) "123abc" 
int(123) 
bool(true)

Could someone explain why $test3 came out true?

using "===" would make that false but that would be due to comparing string to int.

Also notice if I force (string)$test2 it would give me the expected false, and forcing (int)$test1 returns the expected true;

Does this mean $test3 return true because PHP automatically converted $test1 into int before comparison?

Soujirou
  • 109
  • 6
  • 3
    I wish I understood why I so often see PHP examples of `someboolean ? true : false`. If the condition expression is a boolean, the ternary adds no value. – kojiro Jun 20 '14 at 02:43
  • Thanks! Never knew that, always thought you have to have the ternary – Soujirou Jun 20 '14 at 20:48
  • No; in fact even if the condition is not strictly a Boolean, `(bool) $condition` accomplishes the same thing. – kojiro Jun 21 '14 at 01:17

1 Answers1

1

Look at the details here:

a string' == 0 also evaluates to true because any string is converted into an integer when compared with an integer. If PHP can't properly convert the string then it is evaluated as 0. So 0 is equal to 0, which equates as true.

Also, in the official PHP documentation:

To explicitly convert a value to integer, use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument.

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103