I am trying to say $level > -100 && $level < 100
$level = 0;
switch($level){
case $level > -100:
break;
case $level < 100:
break;
default:
echo '5';
return null;
}
can you use a switch statement like this.
None of the answers presented so far have explicitly connected the spirit of the original question with a proper switch construction. So, for the record:
switch (true) {
case (($level>-100) && ($level<100)):
echo 'in range one';
break;
case (($level>200) && ($level<300)):
echo 'in range two';
break;
default:
echo 'out of range';
}
There's absolutely nothing wrong with this usage of switch.
When you say switch ($level) you're already comparing the value of $level. Each case can then only check for equality, you can't do comparisons like in your example. You'll have to use an if statement instead:
if ($level > -100 && $level < 100)
; // do nothing; equivalent of break in this case
else
echo '5';
Even simpler, just negate the conditions:
if ($level <= -100 || $level >= 100)
echo '5';
Apart of if/else, another way to do it:
switch (true)
case $level > -100:
break;
case $level < 100:
break;
default:
echo '5';
return null;
}
The other answers are both correct and incorrect at the same time. Incorrect, in that it is possible to do what you want in PHP... change switch($level) to switch(true) and your example will work. Correct, in that it's bad form and if any other programmers see that in your code they'll probably come after you with pitchforks. Its not how the switch statement is intended to be used, and wouldn't work like that in most other languages.
No you can't. Switch does only 'equals' type comparison.
No, you can't. The switch statement needs literals in the case blocks. Use an if statements instead:
if(!($level > -100 && $level < 100))
{
echo '5';
return null;
}
This is one of the reasons people advocating case as a superior solution to if-else are off base. I don't like the syntax or the limitations - if-ifelse-else is much more useful.
Related
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
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.
I've created a PHP switch / case statement:
switch(true)
{
case ($eff >= '10/2017'):
echo "Greater than 10-2017";
break;
case ($eff <= '09/2017'):
echo "Less thank 10-2017";
break;
default:
echo '';
break;
}
I'm using strtotime to cut down a date from 08/01/2017 to just 08/2017 like this:
$eff = date("m/Y", strtotime($userinfo['ExpDate']));
Unfortunately when I use this to create my case statement it doesn't give me the conditional output. I was hoping for when using a > or < operator and just defaults to the first case statement.
How do I use this to properly use greater/less than?
You can use a solution like the following:
<?php
$eff = date("m/Y", strtotime('10/01/2017'));
$eff = date_create_from_format('m/Y', $eff);
switch(true)
{
case (date_create_from_format('m/Y', '10/2017')->diff($eff)->format('%R%m') >= 0):
echo "Greater than 10-2017";
break;
case (date_create_from_format('m/Y', '09/2017')->diff($eff)->format('%R%m') <= 0):
echo "Less thank 10-2017";
break;
default:
echo '';
break;
}
demo: https://ideone.com/Z2un3C / some tests: https://3v4l.org/YP1Ub
whats wrong with my switch ?
Now result:
< more
> less
= equality
!= no't equality
As it should be:
< more
= equality
<?php
$page = 99;
switch ($page)
{
case $page < 121:
echo '< more <br/>';
case $page > 123:
echo '> less <br/>';
case $page == 99:
echo '= equality <br/>';
case $page != 99:
echo '!= no\'t equality <br/>';
}
?>
In your switch statement you're comparing a number with boolean values.
Let's take the first case $page < 121 is true, so the comparison taking place is 99==true which is true according to http://docs.php.net/language.types.type-juggling (switch performs a loose comparison, not a strict like ===). Thus the first case block is executed.
And since you don't have a break statement it falls through to the next case block and the next and so on...
Meaning: This won't work as intended regardless of whether you use break or not.
You don't seem to understand how switch works. What you want is a series of if statements, i.e.
if ($page < 121)
echo '< more <br/>';
if ($page > 123)
echo '> less <br/>';
if ($page == 99)
echo '= equality <br/>';
if ($page != 99)
echo '!= no\'t equality <br/>';
Switch is to be used only when you want to compare a variable against a set of values.
switch ($variable)
{
case "me":
echo "variable is me";
break;
case "you":
echo "variable is you";
break;
default:
echo "Variable is neither of us";
}
The above switch case block can be written as shown below:
if ($variable=="me")
{
echo "variable is me";
}
elseif ($variable=="you")
{
echo "variable is you";
}
else
{
echo "variable is neither of us";
}
DO NOT put an expression near the case statement.
switch ($somethng)
{
case $something < 10:
break;
case $something > 20:
break;
}
Switch is meant to be used only for comparing a variable against a set of values. ONLY! For everything else use a if...elseif..else statement.
The block above is wrong usage. Sometimes more than one of those expressions could be true.
$var = "cat";
switch($var)
{
case "cat":
echo 'My '.$var.' is called Bob.';
break;
case "dog":
echo 'My '.$var.' is called James.';
break;
default:
echo "I don't have an animal";
break;
}
In a switch statemant you compare $var against value in a case. If there is a match, the actual case will be executed, otherwise the default will be executed. You can't use <>!=... in a case, only values like: 1, '1', 'dog', $var2, and so on.
If you want to run the same command for two case you can do:
$var = "cat";
switch($var)
{
case "cat":
case "dog":
echo 'My '.$var.' is called James.';
break;
default:
echo "I don't have an animal";
break;
}
In your code, your forgot to put break; at the end of each case, that's why you see 'everything' in your output. And you miss default: too.
For the task you're doing, i suggest you to use if statements.
if iam not wrong you can't use this characters < > raw in html. use instead the entities > and <.
if you run the script in the command line i got following output.
<?php
ob_start();
$page = 99;
switch ($page)
{
case $page < 121:
echo '< more <br/>';
case $page > 123:
echo '> less <br/>';
case $page == 99:
echo '= equality <br/>';
case $page != 99:
echo '!= no\'t equality <br/>';
}
$buffer = ob_get_clean();
echo str_replace('<br/>', "\n", $buffer);
output
< more
> less
= equality
!= no't equality
which seems to be the correct behavoir.
It is important to understand how the
switch statement is executed in order
to avoid mistakes. The switch
statement executes line by line
(actually, statement by statement). In
the beginning, no code is executed.
Only when a case statement is found
with a value that matches the value of
the switch expression does PHP begin
to execute the statements. PHP
continues to execute the statements
until the end of the switch block, or
the first time it sees a break
statement.
http://de.php.net/manual/de/control-structures.switch.php
';
break;
case $page > 123:
echo '> less ';
break;
case $page == 99:
echo '= equality ';
break;
case $page != 99:
echo '!= no\'t equality ';
break;
default: echo 'Default';
}
?>
Suppose I have a variable integer and wish to do different things if the value is greater then one value and less then another value. My objective for this switch, is basically to send different results based on the value of $chance, which I will have many cases in the end as this is for a game.
switch ($chance)
{
case ($chance < 15):
echo"strike<br>";
case ($chance < 15 && $chance > 50):
echo"Ball<br>";
break;
case ($chance < 50 && $chance > 100):
echo"Single<br>";
break;
case ($chance <= 150 && $chance >= 100):
echo"double<br>";
break;
case ($chance <= 175 && $chance >= 151):
echo"triple<br>";
break;
case ($chance > 200 && $chance > 175):
echo"Ground Rule Double<br>";
break;
case ($chance < 200):
echo"Home Run<br>";
break;
}
Now, I've been told that I can use conditionals in switch statements, and I've also been told that I should not use them. I really don't know who to believe.
What I do know, is that currently, this switch statement does not work as intended. It doesn't generate syntax errors, but I will get random echos back. This happens when sometimes the chance may be 100 and I will get a home run echo. I'm not sure.
I know I could do the same with a series of if but it would amount to a huge difference in length of code if I can achieve the same results.
I imagine I can do something like
case 1:
echo this
case 2:
echo that
etc etc
Until I hit 2 or 300 but I would like to avoid that if possible.
This is not how you use the switch statement. This is an example of a correct way:
switch ($a) {
case 1:
echo 1;
break;
case 2:
echo 2;
break;
default:
echo 0;
}
For what you want to accomplish you need to use the old if-else statements.
if ($chance < 15)
echo"strike<br>";
else if ($chance >= 15 && $chance < 50)
echo"Ball<br>";
else if ($chance >= 50 && $chance < 100)
echo"Single<br>";
else if ($chance <= 150 && $chance >= 100)
echo"double<br>";
else if ($chance <= 175 && $chance >= 151)
echo"triple<br>";
else if ($chance < 200 && $chance > 175)
echo"Ground Rule Double<br>";
else if ($chance <= 200)
echo"Home Run<br>";
Switch statement syntax:
http://php.net/manual/en/control-structures.switch.php
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>
To do what you are wanting to do, you should use an if-else. The value used for the case expression must be an integer, floating-point decimal, or string.
You need just set true in you switch. Use switch (true) instead of switch ($chance).
now your code will be:
switch (true)
{
case ($chance < 15):
echo"strike<br>";
case ($chance < 15 && $chance > 50):
echo"Ball<br>";
break;
case ($chance < 50 && $chance > 100):
echo"Single<br>";
break;
case ($chance <= 150 && $chance >= 100):
echo"double<br>";
break;
case ($chance <= 175 && $chance >= 151):
echo"triple<br>";
break;
case ($chance > 200 && $chance > 175):
echo"Ground Rule Double<br>";
break;
case ($chance < 200):
echo"Home Run<br>";
break;
}
Despite some mathematical/comparison issues in your code, it seems that you intend to set numeric ranges that correspond to specific outcomes. It also seems inappropriate to reach multiple outcomes in a single script execution.
Given these truths, you should use an if-elseif-else block. It will be more appropriate and less verbose than a switch block.
The ONLY advantage to using a switch block is when you need to make 1 evaluation and take different actions based on that evaluation. Because you are making multiple evaluations, there is no advantage in using a switch -- in fact, the computational complexity will be the same and the syntax will either be of equal or greater length versus an if block. I personally have such a distaste for switch blocks that I endeavor to use any other viable technique instead. Switch blocks only make very rare appearances in my professional projects.
By progressing in an ASC or DESC fashion, you will only need one expression in each condition. Using consistent operators in each condition will make your script easier to maintain/extend.
Finally, in PHP, elseif is one word not two.
Code:
if ($chance < 0) {
$result = 'Balk'; // ;)
} elseif ($chance < 15) {
$result = 'Strike';
} elseif ($chance < 50) {
$result = 'Ball';
} elseif ($chance < 100) {
$result = 'Single';
} elseif ($chance < 150) {
$result = 'Double';
} elseif ($chance < 175) {
$result = 'Triple';
} elseif ($chance < 200) {
$result = 'Ground Rule Double';
} else {
$result = 'Home Run';
}
echo "$result<br>";
I don't understand what's happening here. Logically, it doesn't make any sense to me.
<?php
$level = 0;
switch ($level) {
case $level > 80: $answer = 'high'; break;
case $level > 60: $answer = 'moderate-to-high'; break;
case $level > 40: $answer = 'moderate'; break;
case $level > 20: $answer = 'low-to-moderate'; break;
default: $answer = 'low'; break;
}
echo $answer;
?>
When $level == 0, it returns "high". This doesn't make any sense to me. Can someone explain what's happening here?
Change switch ($level) to switch (true) and this will work.
switch statements perform equality tests on the values in the cases. PHP is evaluating your > comparisons, so case $level > 80 becomes case false. false is considered to be equal to 0, so the first case matches.
The quantity after the case needs to be just the value, not a boolean expression. I'm guessing that PHP is evaluating case $level > 80 as case ($level > 80) which is becoming case 0 (i.e., false, since $level is indeed NOT less than 80) and so you're matching the first case.
Are you sure you can do this in php?
I just checked the manual of switch and you have to provide a distinct value.
I think if you can write it again into something like:
$levelDivTwenty = intval($level/20);
$levelDivTwenty = ($levelDivTwenty>4)?4:$levelDivTwenty;
and then case on that.
switch ($levelDivTwenty) {
case 4: //same as $level > 80 before...
case 3: //>60 etc...
}
As others have pointed out you can't use switch like that, but how about defining it like this:
<?
$level = 21;
$answers = array('low', 'low-to-moderate',
'moderate', 'moderate-to-high', 'high');
echo $answers[intval(($level-1)/20)];
?>
Note: If $level = 0, then expression inside intval() will be -1/20, which is less then -1 and therefore will be rounded to 0.
This isn't really how switch is intended to be used. It's to evaluate for a specific value.
Use an If/else if here, instead of complicating your life to make a switch work like one.