开发者

Is this the way to do this simple IF OR OR statement?

开发者 https://www.devze.com 2023-02-14 02:08 出处:网络
I have an if statement with a few or\'s in it. i.e. if($count == 1||$count == 开发者_如何学C3|| $count == 7) {

I have an if statement with a few or's in it.

i.e.

if($count == 1  ||  $count == 开发者_如何学C3  || $count == 7) {  
    // do stuff
}

I'm just curious - is this the best way to do this? With this simple example above, is there a faster way to do this, and if so, what is it?


Your code works fine. Alternately, you can use in_array(), which is a bit cleaner and scales better:

if (in_array($count, array(1,3,7))) { ... }


The code you've written is fine. As Paul Schreiber says, there are various other options that are a little neater.

One thing you may want to think about (and I know this is just an example) is why the values you're checking are important. Do they all have some property in common that you're checking? If so, then stating the property symbolically may make the code easier for someone to understand. For example:

if (is_odd($x) && $x < 10) {
    //...
}

rather than

if ($x == 1 || $x == 3 || $x == 5 || $x == 7 || $x == 9 ) {
    //...
}

This is quite a contrived example, but hopefully you see what I'm getting at.

As a more concrete example, instead of doing something like:

if ($user->age > 65 
    || $user->years_of_custom > 3
    || $num_items > 5 ) {
       // Give this user a discount ....
}

you might want to do:

if (eligible_for_discount($user, $num_items) ) {
    // Give this user a discount
}

Even if you only use the function in this one place, this could increase the readability of the code. Obviously you have to use your judgment though, because you're increasing readability at the expense of having more lines of code to maintain, and that isn't always the right choice. If the conditions have little to do with each other, binding them up into a separate function might make no sense and make your code harder to follow, not easier. Focus on what your code actually means, and how a human being should understand it.


You can assign all possible value in an array and check using array_search function

$array=array(1,3,7);

if (array_search($count,$array) !== FALSE)
{
  //do stuff
}


Wouldn't the switch statement be better?

switch ($count) {
  case 1:
  case 3:
  case 7:
    echo "do stuff";
    break;
}
0

精彩评论

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