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

Php switch case for specific condition

How should one do a switch case of following condition(-s):

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 returns 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.

Thanks in advance.

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;
}

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;
}