douxiong0668 2013-04-17 19:31 采纳率: 100%
浏览 19
已采纳

PHP IF [FALSE / NULL / EMPTY]功能

Since a year or so I had a function in all my projects called: ifNot().

This function is somehow a derivated from the ternary operator:

public function ifNot( $item, $ifNot )
{
    if ( !$item ) {
        return $ifNot
    } else {
        return $item;
    }
}
// The var $foo twice
$var = ( $foo ) ? $foo : 'is empty or false =(';
// The var $foo once
$var = ifNot($foo, 'is empty or false =(');

In fact, Twig Template Engine use something like it:

{{ foo ? 'yes' : 'no' }}

{# as of Twig 1.12.0 #}
{{ foo ?: 'no' }} == {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} == {{ foo ? 'yes' : '' }}

The question is: There is a better/known approach for this function?

PS: SQL also has an IFNULL() =)

  • 写回答

3条回答 默认 最新

  • dongwei7245 2013-04-17 19:34
    关注

    Your function is essentially equivalent to a variant of the conditional operator that was added in PHP 5.3:

    Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

    It may be a tiny bit faster to use the built-in approach if all your target environments are PHP 5.3 or greater, but I wouldn't really worry about it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用yolov5-7.0目标检测报错
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备