Search code examples
phpcommandsummarize

A way to summarize many commands like if... and if... do


I've created a question and answer page to determine the level of interest of each user for different products like this:
how much u like x (betwin 1-10)
These questions are more than 30, and if I want to write a single command line for each possibilities, it's almost impossible.
the commands do like this:

if $a <=5 and $b <=6 and $c <=7 and... do ...
if $a<= 8 and $b <=7 and $c >= 5 and $d <=8 do...

I want the commands to work this way
Is there a better way to do this?
thanks


Solution

  • For this you could use a switch statement. Documentation: http://php.net/manual/en/control-structures.switch.php

    Example code:

    $i = 10;
    
    switch($i):
        case ($i <= 0): // or for example: case (0)
            return 'It\'s 0 or lower than 0';
            break;
        case ($i > 0 && $i < 10):
            return 'Number is between 0 and 10';
            break;
        case ($i >= 10):
            return 'Number is 10 or higher';
            break;
        default:
            return false;
    endswitch;
    // You can use echo instead of return, but i prefer to use these statements in a function instead of the html page. 
    

    More information about the differences between if and switch is provided by Masivuye Cokile as a comment in your question: Which is Faster and better, Switch Case or if else if?

    I hope this helped. Let me know.