Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 0 || 1 returns true in php?

Tags:

php

In Javascript and Python, 0 || 1 returns 1.

But in PHP, 0 || 1 returns true.

How to do if I want 0 || 1 return 1 in PHP?

another example,

$a is array(array('test'))

I want $a['test'] || $a[0] || array() return array('test'), How to do?

like image 966
clyfish Avatar asked Aug 11 '11 08:08

clyfish


People also ask

What is return true in php?

It returns the boolean TRUE to whatever called dance(). That's all.

Is 0 true or false in php?

0 is the integer value of zero, and false is the boolean value of, well, false.

Is 1 true or false php?

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

How do you check if a variable is true or false in php?

The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.


2 Answers

The other answers appear to only care about converting boolean to an integer. I think you really want for the second value to be the result if the first is falsy (0, false, etc.)?

For the other languages' behaviour, the closest we have in PHP is the short-hand "ternary" operator: 0?:1.

That could be used in your script like: $result = get_something() ?: 'a default';

See the ternary operator documentation for details.

like image 142
salathe Avatar answered Oct 08 '22 22:10

salathe


Because 0 || 1 is a boolean expression, it assumes you want a boolean result.

You can cast it to an int:

echo (int)(0 || 1);
like image 22
Dan Grossman Avatar answered Oct 09 '22 00:10

Dan Grossman