PHP type juggling, "String" == 0 and "String" == true

I have a very simple question. In PHP,

if ('abc' == 0){
if ('abc' == 1){

I know that this page tell us that it is supposed to be like that. But, I find it wierd. In addition,

if ('abc' == true){
if ('abc' == false){

What is the logic behind theses two conversions?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Conversion 1

When string and integer comparisons are made, the string is converted to an integer first and then the comparison is made. Since there are no leading integers in those strings they convert to zero.

Conversion 2

Any non-empty string values are boolean true.

From the manual:

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
array() (an empty array)
$var; (a variable declared, but without a value)

See also: Type Comparisons

Solution 2

The relevant table can be found here. It is important what type both operands have, based on that one or both values will be converted.

In your first case, the rules of both sides being “string, resource or number” is the first applicable, and the rule is “Translate strings and resources to numbers, usual math”.

For the second example, the “Convert both sides to bool, FALSE < TRUE” rule fits.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply