简体   繁体   中英

How many statements are allowed when using ternary operators (? and :) in PHP?

This code,

count = $a > $b ? $b : $a;

same with:

if($a > $b){
   count = $b;
} else {
   count = $a;
}

If I want to do this,

if($a > $b){
   count = $b;
   result = $b." is less than ".$a;
} else {
   count = $a;
}

How should I write these using a ternary operator ? : ? : ...?

You can actually fit this all into 1 line, but it's difficult to read and probably won't work all of the time.

For the sake of showing you this works:

$a = 7;
$b = 5;

$count = 0;
$result = '';

$count = ($a > $b) ? ((int)$result = $b . ' is less than ' . $a) : $a;

echo $count . '<br />' . $result;

But please never do this in any real code - It will make you very unpopular with anyone who has to work on the same code with you/after you.

If you must use the ternary operator in real code, do it as others have suggested.

count = $a > $b ? $b : $a;
result = count == $b ? $b . " is less than " . $a : ""; 

You can't do it in a single line. Sorry.

You really can't, that isn't the point of the ternary operator. You would have to do two statements, or write out the if else.

$count = $a > $b ? $b : $a;
$a > $b ? result = $b." is less than ".$a : ;

Which is I think valid PHP. You may need some parens, and you might need to put a dummy constant after the colon in the second line - just a 0 so PHP has something to do. I'm not sure because I don't PHP.

$result = ($a > $b) ? ("$b is less than $a") : ("$a is less than $b");
$count = ($a > $b) ? $b : $a;

Why you're asking how to make your code worse?
What's the point in making the code totally unreadable?

Do not try to put many statements in the ternary operator.
Do not use nested ternary operators.

You have no only write your code as fast as possible, but sometimes you have to read it .

Instead of using this ugly syntax, use common conditional operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM