开发者

PHP - making this code shorter

开发者 https://www.devze.com 2023-02-04 18:21 出处:网络
I have this PHP code (get_option is Wordpress function). <?php $hahaha = get_option(\'hahaha\'); if(empty($hahaha)) {

I have this PHP code (get_option is Wordpress function).

    <?php $hahaha = get_option('hahaha'); 
    if(empty($hahaha)) { 
       echo 'false'; 
    } 
    else { 
开发者_Python百科       echo 'true'; 
    }
?>

The code looks lame to me, is there a way of making it shorter like (my imagination ;)):

<?php $hahaha = get_option('hahaha');
if($hahaha): 'true' // 'false'
?>


You can use a ternary operator, but I'm not sure it does much for readability:

echo (empty($hahaha) ? 'false' : 'true');


$hahaha = get_option('hahaha'); 
echo $hahaha ? 'true' : 'false';

There's no need for empty, since the variable is definitely set. A pure boolean comparison works just fine.

If you don't need the variable later on for something else, you can skip it as well:

echo get_option('hahaha') ? 'true' : 'false';


$hahaha = get_option('hahaha');
echo empty($hahaha) ? 'true' : 'false';

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


echo empty($hahaha)?'false':'true';


echo empty($hahaha = get_option('hahaha')) ? 'false' : 'true';


This will display 0 or 1

$options = get_options(...);

echo empty($options); OR echo !empty($options);


<?php $hahaha = get_option('hahaha');
echo (isset($hahaha)) ? 'true': 'false';
0

精彩评论

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