Triple operators in php?

Possible duplicates:
Link - what does this symbol mean in PHP?
To ternary or not to ternary?

Can someone explain the advantages / disadvantages or use the ternary operator instead of the if / else statement. Where and when should I use each?

+2
source share
5 answers

Ternary operators are shorter (which is good for writeability) than if there were else statements, however you really should use them only when working with one condition. Nested ternary operators really reduce readability.

In general, I only use ternary operators when:

1) I assign a condition based variable.

and

2) There is only one condition.

, .

:

$port = ($secure) ? 443 : 80;

a if else :

if($secure){
  $port = 443;
} else {
  $port = 80;
}

:

$port = 80;
if($secure){
  $port = 443;
}

, ( , ).

, , , . , , , . , - . , .

, .

$count++

.

$count = $count + 1 // or $count += 1

, , , 9-10 $count++, .

+12

, . , , if/else , .

$result = $condition > 5 ? "hello" : "world";

// is clearer & easier to read than
if ($condition > 5)
{
  $result = "hello";
}
else 
{
  $result = "world";
}
+2

, , , , , . , :

$foo = $bar == 1 ? 'a' : $bar == 2 ? 'b' : 'c';

, $bar 1, $foo? "a", ! PHP:

php > $bar = 1; $foo = $bar == 1 ? 'a' : $bar == 2 ? 'b' : 'c'; echo $foo;
b
php > $bar = 2; $foo = $bar == 1 ? 'a' : $bar == 2 ? 'b' : 'c'; echo $foo;
b

! PHP. parens :

$foo = $bar == 1 ? 'a' : ($bar == 2 ? 'b' : 'c');

. , . if-elseif-else, if.

+1

if/else . . :

$a = (condition ? 1 : 2)

if (condition) {
 $a=1
}
else {
 $a=2
}
0
  • :
  • :

: .

PHP . , .
if,

if($age < 18) $error = "Too young!";

:

If [this] age is less than 18, the error will be "too young"

but how would you read such a triple

$error = (($age < 18))? "Too young":"";

?

Will the error be under the age of 18? Too young! [some noise].

-2
source

All Articles