Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is true greater than 3 in PHP

Tags:

types

php

casting

I am wondering why following statement in PHP is returning true?

true>=4

for example such line will echo 1

echo true>=4;

Can anyone explain me the logic behind this?

like image 843
Dharman Avatar asked Dec 04 '12 21:12

Dharman


2 Answers

In addition to Davids answer, I thought to add something to give a little more depth.

PHP unlike other programming languages, if your not careful with your operators/syntax you can fall into tricky pot holes like the one you experience.

As David said,

4 is also true (because it's non-zero), and true is equal to true, so it's also greater than or equal to true.

Take this into account True is greater than false.

true = 1

false = 0

So take this for example:

$test = 1;
if ($test == true){
echo "This is true"; 
}else{
echo "This is false";
}

The above will output

This is true

But if you take this:

$test = 1;
if ($test === true){
echo "This is true"; 
}else{
echo "This is false";
}

The above will output:

This is false

The added equals sign, looks for an exact match, thus looking for the integer 1 instead of PHP reading 1 as true.

I know this is a little off topic, but just wanted to explain some pot holes which PHP contains.

I hope this is some help

Edit:

In response to your question:

echo true>=4;

Reason you are seeing 1 as output, is because true/false is interpreted as numbers (see above)

Regardless if your doing echo true>=4 or just echo true; php puts true as 1 and false as 0

like image 74
Daryl Gill Avatar answered Oct 14 '22 11:10

Daryl Gill


4 is also true (because it's non-zero), and true is equal to true, so it's also greater than or equal to true.

If a bool or null is compared to anything other than a string, that thing is cast to a bool. See the docs.

like image 24
David Schwartz Avatar answered Oct 14 '22 11:10

David Schwartz