Jump to content

using range in switch


TheSky

Recommended Posts

This is an interesting question, as my original thought was thought you can't use a case block to check for ranges of values. However, after a search on google, I came across the following solution

 

If you use a boolean value as the argument to the switch value, then you can use conditions in the case statements. THose that evaluate to true will be the ones that one. For example

$t = 25;
switch(true){
case ($t > 0 && $t <= 20)://the range from 1-20
	echo "1";
	break;
case ($t > 20):
	echo "2";
	break;
}

 

that echos "2".

 

However, this solution isn't really any better than using if-else if statements together, and syntactically I don't think using ifs would be any more work than the case statement

 

EDIT: if you wanted to use range, you would want to use in_array as part of your condition, ala

 

switch(true){
case (in_array($t, range(0,20))://the range from range of 0-20
	echo "1";
	break;
case ($in_array($t, range(21,40))//range of 21-40:
	echo "2";
	break;
}

Link to comment
Share on other sites

hmm i tryed this is not working :(

Parse error: syntax error, unexpected ':' in ...

i need just like that function

switch(true){
case (in_array($t, range(0,20))://the range from range of 0-20
echo "1";
break;
case ($in_array($t, range(21,40))//range of 21-40:
echo "2";

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.