John Doe 2 John Doe 2 - 2 months ago 7
PHP Question

switch case for specific conditions

How should one do a switch case of following conditions:

Case 1 would look like this for instance:

if($this->hasA() && $this->hasB() && $this->hasC() && $this->hasD())
{
# ....
}


Case 2 could look like this and so on:

if($this->hasA() && $this->hasB())
{
# ....
}


The functions return a boolean value.

This may be not a good practice to do, but I would like to know how this would look like in a switch case.

Answer

I personally wouldn't do this over the if, but you can switch on true:

switch(true) {
    case $this->hasA() && $this->hasB() && $this->hasC() && $this->hasD():
        //code
        break;

    case $this->hasA() && $this->hasB():
        //code
        break;
}

Keep in mind that the functions are executed for each case ($this->hasA() and $this->hasB() twice in above code), so if they are expensive (complex queries, file loads, etc.) then you are better off running them once and then checking the result multiple times.

If any of the cases share some code then you would structure it in order and not use break so that one case would execute through to the next. It's not clear from your example if some have common code.

A simple example:

switch(true) {
    case $this->hasA():
        //code

    case $this->hasB():
        //case above may or may not execute
        //more code

    case $this->hasC():
        //one or both cases above may or may not execute
        //more code
        break;
}
Comments