clyfish
clyfish

Reputation: 10460

Why 0 || 1 returns true in 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?

Upvotes: 6

Views: 2624

Answers (7)

Greenisha
Greenisha

Reputation: 1437

You can use casting to integer

echo (int)(0||1);

Upvotes: 1

salathe
salathe

Reputation: 51950

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.

Upvotes: 12

Mchl
Mchl

Reputation: 62395

Cast the result to int ;P (int)(0 || 1)

Although it will work only for 1. (int)(0 || 2) will return 1 as well.

Upvotes: 1

Dan Grossman
Dan Grossman

Reputation: 52372

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);

Upvotes: 9

user703016
user703016

Reputation: 37975

In PHP the operator || returns a boolean, either true or false.

What you probably want is something like this: $result = (0 || 1) ? 1 : 0;

Upvotes: 3

user684934
user684934

Reputation:

if(0||1)
    return 1;
else return 0;

Upvotes: 1

cdhowie
cdhowie

Reputation: 169143

You could use

(0 || 1) ? 1 : 0

Upvotes: 2

Related Questions