Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP boolean TRUE / FALSE?

Tags:

php

boolean

I can't figure this out.

If I type:

function myfunction(){
    ......
    if ...
        return TRUE;
    if ...
        return FALSE;
}

Why can't I use it like this:

$result = myfunction();
if ($result == TRUE)
...
if ($result == FALSE)
...

Or do I have to use:

$result = myfunction();
if ($result == 1)
...
if ($result == 0)
...

Or this:

$result = myfunction();
if ($result)
...
if (!$result)
...
like image 232
never_had_a_name Avatar asked Dec 07 '09 06:12

never_had_a_name


People also ask

Is 1 true or false in PHP?

Value 0 and 1 is equal to false and true in php.

Is it true 0 or 1?

Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true. To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.

Is 0 true or false in PHP?

string – “0” and null string are false and everything else is true (even “0.0”) array – empty array is false and everything else is true. object – here null is false and everything else is true. null – null is always false.

Is bool 1 True or false?

Boolean values and operationsConstant true is 1 and constant false is 0. It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0.


1 Answers

I don't fully understand your question, but you can use any of the examples you provided, with the following caveats:

If you say if (a == TRUE) (or, since the comparison to true is redundant, simply if (a)), you must understand that PHP will evaluate several things as true: 1, 2, 987, "hello", etc.; They are all "truey" values. This is rarely an issue, but you should understand it.

However, if the function can return more than true or false, you may be interested in using ===. === does compare the type of the variables: "a" == true is true, but "a" === true is false.

like image 165
Tordek Avatar answered Oct 04 '22 04:10

Tordek