开发者

Correct Ternary Condition for IF ElseIf Condition

开发者 https://www.devze.com 2023-02-19 20:22 出处:网络
Here is my If Else Statement if(isset($row[\'content\']) && strlen($row[\'content\'])) { $content = $row[\'content\'];

Here is my If Else Statement

if(isset($row['content']) && strlen($row['content'])) {
  $content = $row['content'];
}
elseif(is开发者_开发百科set($row['description']) && strlen($row['description'])) {
  $content = $row['description'];
}

I tried to create a condition using ternerary operator and ended for with a error: Here is my ternerary condition

$content = isset($row['content']) && strlen($row['content']) ? $row['content'] : isset($row['description']) && strlen($row['description']) ? $row['description'] : '';

What is the correct statement?


You're making your code very very unreadable by changing your condition into a ternary operator. Anyhoo, the following works without an error.

$content =  (isset($row['content']) && strlen($row['content'])) 
        ? $row['content'] 
        : (isset($row['description']) && strlen($row['description']) 
            ? $row['description'] 
            : '');

Wrapped the last expression in parenthesis so PHP doesn't try to evaluate it separately.


Try putting inside bracket the first term of ?: and the last term of first ?:.

$content = (isset($row['content']) && strlen($row['content'])) ? $row['content'] : ((isset($row['description']) && strlen($row['description'])) ? $row['description'] : '');
0

精彩评论

暂无评论...
验证码 换一张
取 消