Why 0 || 1 returns true in php?

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

But in PHP, 0 || 1 0 || 1 returns true.

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

another example,

$a array(array('test'))

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

+6
source share
7 answers

The rest of the answers seem to worry only about converting a boolean to an integer. I think you really want the second value to be the result if the first is false ( 0 , false , etc.)?

For the behavior of other languages, the shortest ternary operator: 0?:1 is closest to PHP.

This can be used in a script like: $result = get_something() ?: 'a default';

See the ternary operator documentation for more information.

+12
source

Since 0 || 1 0 || 1 is a logical expression, it is assumed that you want to get a logical result.

You can pass it to int:

 echo (int)(0 || 1); 
+9
source

In PHP, the || returns a boolean value: true or false.

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

+3
source

you can use

 (0 || 1) ? 1 : 0 
+2
source
 if(0||1) return 1; else return 0; 
+1
source

You can use casting for integer

 echo (int)(0||1); 
+1
source

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

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

+1
source

Source: https://habr.com/ru/post/894799/


All Articles