TheSky Posted June 13, 2011 Share Posted June 13, 2011 how to use range in swich i want get values from $ like switch($value){case range(' 2,4 '): $value='First'; break; case range(' 5,7 '): $value='Second'; break;} Link to comment https://forums.phpfreaks.com/topic/239198-using-range-in-switch/ Share on other sites More sharing options...
mikesta707 Posted June 13, 2011 Share Posted June 13, 2011 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 https://forums.phpfreaks.com/topic/239198-using-range-in-switch/#findComment-1228921 Share on other sites More sharing options...
TheSky Posted June 13, 2011 Author Share Posted June 13, 2011 thanks allot ! Link to comment https://forums.phpfreaks.com/topic/239198-using-range-in-switch/#findComment-1228969 Share on other sites More sharing options...
TheSky Posted June 13, 2011 Author Share Posted June 13, 2011 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 https://forums.phpfreaks.com/topic/239198-using-range-in-switch/#findComment-1228978 Share on other sites More sharing options...
TheSky Posted June 13, 2011 Author Share Posted June 13, 2011 seems im stuck with value geting from echo but i think that code what did you write was correct Link to comment https://forums.phpfreaks.com/topic/239198-using-range-in-switch/#findComment-1228989 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.