tags:

views:

116

answers:

3

I'm not sure what to call this, so I'll give an example.

In PHP

1==2 || 2 returns 1 or true

In Ruby

1==2 || 2 returns 2 (The second statement if the first evaluates to false).

Is there any short way to implement similar thing in PHP?

A: 

In PHP, the result of boolean expressions is always a boolean. So 1==2 || 2 gives true.

The best thing I can think of is

($var = 1 == 2) || ($var = 2)

Then $var will be 2.

Depending on the answer to Matchu's question, you may want:

(($var = 1) == 1) || ($var = 2)

or

($var = 1 == 1) || ($var = 2)
Artefacto
A: 

How about 1 == 2 or 2?

However, the result might not be the same if you print directly, so you need to put the result inside a variable. Take this example:

$result = "a" or 2;
var_dump($result); // prints string(1) "a"

var_dump("a" or 2); // prints bool(true)

Take a look here: http://www.php.net/manual/en/language.operators.logical.php

treznik
`$result = "a" or 2;` evaluates to "a" because `=` has higher precedence than `or`.`$result = false or true` sets $result to false.
Adam
I see. So the you can't use the `or` operator for this scenario?
treznik
+1  A: 

How about

1==2 ? 1==2 : 2

or in PHP 5.3

1==2 ?: 2
newacct
I think 2nd one would be the shortest piece of code. Too bad its PHP 5.3+ only.
Adam