acctman
acctman

Reputation: 4349

PHP shorthand if/else ternary

How can I make this a one or two line shorthand ternary?

if ($tame == null): 
    echo $tame = '0' . '<br />';
else: 
    echo $tame . '<br />';
endif;

Upvotes: 1

Views: 4354

Answers (8)

sachleen
sachleen

Reputation: 31131

echo $tame == null ? $tame = '0<br />' : $tame.'<br />';

Upvotes: 2

joemaller
joemaller

Reputation: 20556

If $tame is null or an integer, you can skip the logic altogether:

echo sprintf("%d<br />", $tame);

This assumes you didn't mean to assign "0<br />" to $tame in the second line, as pointed out by @mellamokb.

Upvotes: 0

Reactgular
Reactgular

Reputation: 54751

Looks like the OP is expecting $tame to be an integer value. Why else would he write zero for null?

If this is the case. This is the shortest solution.

echo (int)$tame.'<br/>';

That will echo 0 for null or a numeric value. There is also no reason to set $tame to zero, because PHP treats null and zero the same.

Upvotes: 4

John Conde
John Conde

Reputation: 219804

echo (is_null($tame)) ? '0<br />' : $tame . '<br />';

Upvotes: 0

Hawili
Hawili

Reputation: 1659

How about one more way :)

echo $tame . (!is_null($tame)?:'0'). '<br />';

as you can see I omitted the middle part, since php 5.3 you can do it like this

The ternary part is only the part which is needed to be printed you can still do it like this for older php

echo $tame . (is_null($tame)?'0':''). '<br />';

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179046

The ternary operator is essentially an if..else statement in one line.

if (condition) {
    action(a);
} else {
    action(b);
}

turns into:

action( condition ? a : b );

What you have is:

if ($tame == null) {
    echo $tame = '0' . '<br />';
} else {
    echo $tame . '<br />';
}

which could be written as:

echo $tame == null ? $tame = '0<br />' : $tame . '<br />';

However, this ternary statement is relatively complex, given that $tame is being mutated as part of the statement. Code written this way is harder to read, and therefor difficult to debug, which makes it more prone to errors. It would be better overall if you wrote the code in the more verbose form:

if ($tame == null) {
    $tame = '0';
}
echo $tame . '<br />';

Upvotes: 1

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

echo ($tame == null ? ($tame = 0) : $tame), '<br />';

Upvotes: 1

mellamokb
mellamokb

Reputation: 56769

$tame = ($tame == null) ? 0 : $tame;
echo $tame . '<br />';

Upvotes: 3

Related Questions