doukao5073 2014-05-27 18:31
浏览 85
已采纳

PHP比较效率($ var ==($ var1 || $ var2))

I was wondering if there's a more efficient way to do the following if:

if($var == $var1 || $var == $var2)

I thought of

if($var == ($var1 || $var2)) but that doesn't work at all. Excuse my noobish question, I never asked myself such a simple thing.

  • 写回答

4条回答 默认 最新

  • drhdjp97757 2014-05-27 18:38
    关注

    If we assume that you're taking 'efficiency' to mean run time (vs other measures such as number of keystrokes, e.g.) then what you originally have is as efficient as it gets:

    if($var == $var1 || $var == $var2)
    

    Conditional operators || and && short circuit when they can, meaning if $var happens to equal $var1, then the comparison against $var2 will never take place.

    If you start to have many many conditions are you're just looking to keep your code clean, you can store all of the possible values in an array and check to see if $var is in the array:

    $possibleVals = array( 1, 2, 3 );
    $var = 1;
    if(in_array($var, $possibleVals)) {
        // ...
    

    That, however, is not nearly as efficient in terms of running time than if you listed out all of the comparisons individually (for a nominal number of elements you most likely wouldn't even notice a difference, though).

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

报告相同问题?

悬赏问题

  • ¥15 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。
  • ¥20 网站后台使用极速模式非常的卡
  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)