I cannot get my head around this. There might be a simple solution and the problem addressed already, but I could not find an answer.
<?php
$string = '';
$array = array(1, 2, 3);
foreach($array as $number) {
switch($number) {
case '1':
$string .= 'I ';
case '2':
$string .= 'love ';
case '3':
$string .= 'you';
}
}
echo $string;
?>
As you might have guessed, the sentence produced should be: I love you
But that is the actual output: I love youlove youyou
How is this even possible, when the switch is only triggered thrice.
Meanwhile I know that the problem can be fixed with a >break;< after each case. But I still do not understand why this is necessary.
I would be very happy, if someone could explain to me what PHP is doing.
Happy Valentines!
When case 1 is matched it will also execute case 2 and 3 unless there is a break.
So each time through the loop the matched case and everything following is executed.
First time: case 1, 2, 3
Second time: case 2, 3
Third time: case 3
For reference, here's an extract from the PHP documentation on switch, which explains it better than I probably would. :)
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. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
}
?>
Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).
When you don't specify a break the code execution will fall-through to the next case.
As an example an exam paper with a score out of 10 could be graded as such:
switch ($score)
{
case 10:
// A+ when score is 10
echo 'A+';
break;
case 9:
case 8:
// A when score is 8 or 9
echo 'A';
break;
case 7:
case 6:
// B when score is 7 or 6
echo 'B';
break;
case 5:
case 4:
case 3:
// C when score between 3 and 5
echo 'C';
break;
default:
// Failed if score is less than 3
echo 'Failed';
}
Related
if (substr('xcazasd123', 0, 2) === 'ax'){
}
Above code is working where it able to check if the "variable" is
starting with 'ax', but what if i wanted to check "multiple"
different validation ?
for example : 'ax','ab','ac' ? Without creating multiple if statement
You can use array to store your keywords and then use in_array() if you want to avoid multiple if statements.
$key_words =["ax","ab","ac"]
if (in_array( substr('yourstringvalue', 0, 2), $key_words ){
//your code
}
References:
in_array — Checks if a value exists in an array
If this sub-string is always in the same place - easy and fast is switch
// $x = string to pass
switch(substr($x,0,2)){
case 'ax': /* do ax */ break;
case 'ab': /* do ab */ break;
case 'ac': /* do ac */ break; // break breaks execution
case 'zy': /* do ZY */ // without a break this and next line will be executed
case 'zz': /* do ZZ */ break; // for zz only ZZ will be executed
default: /* default proceed */}
switch pass exact values in case - any other situation are not possible or weird and redundant.
switch can also evaluate through default to another one switch or other conditions
manual
You can use preg_match approach for test the string:
if(preg_match('/^(ax|ab|ac)/', '1abcd_test', $matches)) {
echo "String starts with: " . $matches[1];
} else {
echo "String is not match";
}
Example: PHPize.online
You can learn about PHP Regular Expressions fro more complicated string matching
This question already has answers here:
switch statement with multiple cases which execute the same code
(3 answers)
Closed 5 years ago.
I want to store a certain value during a switch/case in PHP, but I don't see what is wrong with this code:
<?php
$weegfactor=67;
$lus=12;
if($weegfactor<70):
switch($lus){
case(1 || 7):
$verdeling="AAABCD";
break;
case(2 || 8):
$verdeling="AAABBE";
break;
case(3 || 9):
$verdeling="AAAABC";
break;
case(4 || 10):
$verdeling="AABBBD";
break;
case(5 || 11):
$verdeling="ABBBCC";
break;
case(6 || 12):
$verdeling="AABCCC";
break;
}
endif;
echo "weegfactor ",$weegfactor . '</br>' ;
echo "lus : ",$lus . '</br>';
echo "verdeling ",$verdeling;
?>
The outcome of the above code is:
weegfactor 67
lus : 12
verdeling AAABCD
Which is not correct because $verdeling should be "AABCCC".
What is my mistake??
1 || 7 evaluates to a boolean type. So your program is doing a boolean comparison of $lus and (1 || 7).
You will need to use two separate case statements for each:
switch($lus){
case(1):
case(7):
$verdeling="AAABCD";
break;
case(2):
case(8):
$verdeling="AAABBE";
break;
case(3):
case(9):
$verdeling="AAAABC";
break;
case(4):
case(10):
$verdeling="AABBBD";
break;
case(5):
case(11):
$verdeling="ABBBCC";
break;
case(6):
case(12):
$verdeling="AABCCC";
break;
}
With case (x || y) you probably mean when it is x or y. In that case you should do this:
switch($lus) {
case x:
case y:
// do stuff
break;
}
What you have now is a check against x || y, which is always resolves to a "truish" value, just like your value 12 is "truish", making the switch take the first branch.
The value of 1 || 7 is TRUE, because both 1 and 7 are truthy. So the first case is equivalent to:
case TRUE:
And in fact, all your cases are equivalent to case TRUE:.
So it's then testing $lus == TRUE. When comparing any type to a boolean, the other type is first converted to boolean (see Comparison Operators for the complete list of how loose comparisons of different types are done). Since 12 is truthy (any non-zero integer is truthy), this comparison succeeds.
If you want to test against multiple values, use multiple case statements:
case 1:
case 7:
$verdeling="AAABCD";
break;
Code:
switch ($_GET['operation']) {
case "professionist":
case "company":
case "student":
echo "ok<br>";
case "professionist":
echo "inprofessionist<br>";
break;
case "company":
echo "incompany<br>";
break;
default:
echo "Meh!<br>";
break;
}
My goal is to execute some (common to professionist/company/student) code first, and then execute the rest of the code depending on the operation...
The problem is that the first 3 cases works perfectly, but then, if for example the operation is "company", the switch go on "professionist" case, what i'm doing wrong? How can improve that? Thanks in advance...
That's how switch works. If you always need to print "ok" then move it outside switch:
$op = $_GET["operation"];
if (in_array($op, array("professionist", "company"))) {
echo "ok<br>";
}
switch ($op) {
case "professionist":
echo "inprofessionist<br>";
break;
case "company":
echo "incompany<br>";
break;
default:
echo "Meh!<br>";
break;
}
Only the first case with a given value will ever be targeted by a switch. (And in fact, a switch only ever goes to a single case per execution - fallthough just lets you have multiple cases share some code, but only one of them is what's actually triggered.)
Thus, it doesn't make sense to have multiple casees with the same value that they're looking for - a switch statement isn't the same thing as a series of independent ifs; it's a mapping of jump targets.
Essentially, let's say you have a switch like this:
w; // 001
switch ($foo) { // 002
case 'a':
w; // 003
case 'b':
x; // 004
break; // 005
case 'c':
y; // 006
}
z; // 007
What actually winds up effectively happening is that you get some code effectively like this (note: highly simplified from how this actually works):
001 v
002 jump based on $foo: [a -> 003, b -> 004, c -> 006]
003 w
004 x
005 jump to 007
006 y
007 z
and then that program just gets run from top to bottom.
In the case where $foo is 'a', it jumps to 003 and runs from there, which means that it winds up doing v,jump,w,x,z in total.
In the case where $foo is 'b', it jumps to 004 and runs from there, which means that it winds up doing v,jump,x,z in total.
In the case where $foo is 'c', it jumps to 006 and runs from there, which means that it winds up doing v,jump,y,z in total.
I'm quite used to vb.net's Select Case syntax which is essentially a switch statement, where you can do things like Case Is > 5 and if it matches, it will execute that case.
How can I do what I'm going to call "conditional switch statements" since I don't know the actual name, in PHP?
Or, what's a quick way to manage this?
switch($test)
{
case < 0.1:
// do stuff
break;
}
That's what I've tried currently.
I think you're searching for something like this (this is not exactly what you want or at least what I understand is your need).
switch (true) finds the cases which evaluate to a truthy value, and execute the code within until the first break; it encounters.
<?php
switch (true) {
case ($totaltime <= 1):
echo "That was fast!";
break;
case ($totaltime <= 5):
echo "Not fast!";
break;
case ($totaltime <= 10):
echo "That's slooooow";
break;
}
?>
I tried to add this as a comment to the answer by BoltCock, but SO is telling me that his answer is locked so I'll make this a separate (and essentially redundant) answer:
The "switch(true)" answer from BoltCock is much like the following example, which although logically equivalent to if + else if + else is arguably more beautiful because the conditional expressions are vertically aligned, and is standard/accepted practice in PHP.
But the if + else if + else syntax is essentially universal across scripting languages and therefore immediately readable (and maintainable) by anyone, which gives it my nod as well.
There is an additional way you can accomplish this, in PHP 8.0+, by using a match statement.
If you have a single expression within each case, it is equivalent to the following match statement. Note that unlike switch statements, we can choose to return a variable (in this code I am storing the result in $result).
$test = 0.05;
$result = match (true) {
$test < 0.1 => "I'm less than 0.1",
$test < 0.01 => "I'm less than 0.01",
default => "default",
};
var_dump($result);
Match statements only allow you to have a single expression after each condition. You can work around this limitation by calling a function.
function tinyCase(){}
function veryTinyCase(){}
function defaultCase(){}
$test = 0.01;
match (true) {
$test < 0.1 => tinyCase(),
$test < 0.01 => veryTinyCase(),
default => defaultCase(),
};
And for reference, if you just want to check for equality you can do:
$result = match ($test) { // This example shows doing something other than match(true)
0.1 => "I'm equal to 0.1",
0.01 => "I'm equal to 0.01",
default => "default",
};
Match statements do have some key differences from switch statements that you need to watch out for:
My last example will use a strict equality check === instead of a loose one ==.
If a default case is not provided, an UnhandledMatchError error is thrown when nothing matches.
And there is no worrying about falling through to the next case if you forget to add break.
PHP supports switch statements. Is that what you wanted?
Switch statement with conditions
switch(true)
{
case ($car == "Audi" || $car == "Mercedes"):
echo "German cars are amazing";
break;
case ($car == "Jaguar"):
echo "Jaguar is the best";
break;
default:
echo "$car is Ok";
}
Is it possible to use "or" or "and" in a switch case? Here's what I'm after:
case 4 || 5:
echo "Hilo";
break;
No, but you can do this:
case 4:
case 5:
echo "Hilo";
break;
See the PHP manual.
EDIT: About the AND case: switch only checks one variable, so this won't work, in this case you can do this:
switch ($a) {
case 4:
if ($b == 5) {
echo "Hilo";
}
break;
// Other cases here
}
The way you achieve this effectively is :
CASE 4 :
CASE 5 :
echo "Hilo";
break;
It's called a switch statement with fall through. From Wikipedia :
"In C and similarly-constructed languages, the lack of break keywords to cause fall through of program execution from one block to the next is used extensively. For example, if n=2, the fourth case statement will produce a match to the control variable. The next line outputs "n is an even number.". Execution continues through the next 3 case statements and to the next line, which outputs "n is a prime number.". The break line after this causes the switch statement to conclude. If the user types in more than one digit, the default block is executed, producing an error message."
No, I believe that will evaluate as (4 || 5) which is always true, but you could say:
case 4:
case 5:
// do something
break;
you could just stack the cases:
switch($something) {
case 4:
case 5:
//do something
break;
}
switch($a) {
case 4 || 5:
echo 'working';
break;
}