Limit the value of a variable to certain predefined values

What is the shortest and easiest way to do this?

For instance:

$var = $_GET['something']; // how to limit the value of $var to "10", "20", "30", "40", // and "" for any other input ? 

I mean, is there a php helper function that can do this without using 5 IFs?

+4
source share
5 answers

in_array is suitable in this case:

 if(!in_array($var, array("10", "20", "30", "40")) { // $var will be "" if it does not equal: "10", "20", "30", or "40" $var = ""; } 
+7
source

Yes, you can create a predefined array and then validate it:

 $array = (10, 20, 30, 40); if(in_array($array, $var)){ // validated } else { // invalid } 
+2
source

restriction or check?

 if (isset($_GET['something'])) { $validSomethings = array("10", "20", "30", "40"); foreach ($validSomethings as $something) { if ($something == $_GET['something']) { // it valid. do it. } else { // not valid } } } 
+1
source

And a more unconventional method:

 $map = array(10, 20, 30, 40); // == range(10, 40, 10); $map = array_combine($map, $map); $value = "{$map[$_GET['something']]}"; 

It has the advantage of implicitly generating a notification of unwanted parameters (for logging).

+1
source

It is not clear what you are asking. There are many alternatives to 5 ifs. You can use math to limit answers.

 $var = (is_numeric($var))?(($var>40 || $var < 10)?"":floor($var/10)*10):""; 

You can use one operator.

 switch($var){ case "10": case "20": case "30": case "40": //do something? break; default: $var = ""; //do something else? break; } 
+1
source

All Articles