Wordpressor
Wordpressor

Reputation: 7553

PHP if shorthand and echo in one line - possible?

What's the best, preferred way of writing if shorthand one-liner such as:

expression ? $foo : $bar

Plot twist: I need to echo $foo or echo $bar. Any crazy tricks? :)

Upvotes: 26

Views: 87914

Answers (5)

asim usman
asim usman

Reputation: 19

   // check if it value is true then display value otherwise it display empty or ''
    <?= $color ? $color : ''; ?>
   // same thing if condition is true then display Condition is true otherwise display Condition is false
    <?php echo $condition ? 'Condition is true' : 'Condition is false';?>

Upvotes: -1

user2472505
user2472505

Reputation:

Great answers above, and I love when programmers ask questions like this to create clear, concise and clinical coding practices. For anyone that might find this useful:

<?php

// grabbing the value from a function, this is just an example
$value = function_to_return_value(); // returns value || FALSE

// the following structures an output if $value is not FALSE
echo ( !$value ? '' : '<div>'. $value .'</div>' ); 

// the following will echo $value if exists, and nothing if not
echo $value ?: '';
// OR (same thing as)
echo ( $value ?: '' ); 

// or null coalesce operator
echo $value ?? '';
// OR (same thing as)
echo ( $value ?? '' );

?>

References:

Upvotes: 0

A.M.N.Bandara
A.M.N.Bandara

Reputation: 1508

echo (expression) ? $foo : $bar;

Upvotes: 12

Dave
Dave

Reputation: 2994

<?=(expression) ? $foo : $bar?>

edit: here's a good read for you on the topic

edit: more to read

Upvotes: 66

user2044560
user2044560

Reputation:

The ternary operator evaluates to the value of the second expression if the first one evaluates to TRUE, and evaluates to the third expression if the first evaluates to FALSE. To echo one value or the other, just pass the ternary expression to the echo statement.

echo expression ? $foo : $bar;

Read more about the ternary operator in the PHP manual for more details: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

Upvotes: 7

Related Questions