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";
}
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
So I know you could do something simple like this to set a variable equal to one thing if the condition is true and one thing if it is false.
$height > 70 ? $output = "Taller than 6 foot" : $output = "Shorter than 6 foot";
But how would I go through and check multiple things like this not using an if statement? For example, if I wanted to check if height was between 5 and 6, between 4 and 5, between 3 and 4 and more, and then only echo out one $result based on which category $height fell in, how would I do that? Could I just add something useless after the : such as a variable I would never use?
The only way to parameterize this would be to use switch which is mostly the same as using ifs but with a multiple verifications. Sadly, there's no shorter way to write this. (There might be, but they might be cumbersome to write / read which is not always an advantage!).
Here's a switch / case statement that uses multiple conditions. Usually, you pass the variable to the switch statement and you use the case statements with variables or possible values, but since the possible values are conditions, you need to pass true as a parameter as this is the value to be expected. You can reverse this by passing false if needed.
switch(true){
case ($my_number > 3):
echo "Greater than 3";
break;
case ($my_number <= 3):
echo "Smaller or equal to 3";
break;
}
you can make nested conditions:
$output = ($height < 6 && $height > 5) ? 'something' : (($height <= 3) ? 'less t. 3' : 'over 4')
but this is not really readable, I would avoid this, syntax with multiple conditions is better with if/switch
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';
}
This is just a simple check to see what letter grade to output. Is there any faster and more efficient way to achieve the objective?
if ( $grade >= 90 ) {
echo "A";
} elseif ( $grade >= 80 ) {
echo "B";
} elseif ( $grade >= 70 ) {
echo "C";
} else {
echo "Failed."
}
This is not answering your actual question but I think you are making a mistake here:
You really shouldn't be thinking about efficiency when using PHP, it is not a language that was designed for speed, but one that was designed for ease of use. Even more so if your application is not yet finished and you haven't verified that this piece of code slows down your whole application (using the profiler of xdebug, for example).
Any such improvements would be micro-optimizations. I think you've got the best solution for both efficiency and clarity.
I agree with other posters that you're doing it right already. However, in situations like these you could could try converting the $grade to a value that could be used as an index in an associative array, not unlike what #ghostdog74 tried to do above.
$gradeindex = (int)$grade / 10; // 10 since we want 10-19 = 1, etc..
$gradenames = array('10' => 'A+', '9' => 'A', '8' => B, ..... );
However, since so many of them are identical, I'd probably use a switch()
$gradeindex = (int)$grade / 10; // 10 since we want 10-19 = 1, etc..
switch ($gradeindex) {
case 10:
case 9:
$gradename = 'A';
break;
case 8:
$gradename = 'B';
break;
case 7:
$gradename = 'C';
break;
default:
$gradename = 'Failed';
}
echo $gradename;
But as already said, you're basically best of with your current if statement.
I'm sure there are weird ninja ways to do what you're doing, but yours is certainly the best. It's the most clear to read, and performance wise it's too fast to matter.
Personally, I think I would use a function with multiple returns for this purpose:
function intGradeToStrGrade($grade) {
if ($grade >= 90) return "A";
if ($grade >= 80) return "B";
...
}
However, there has been some debate here on SO if multiple returns in one function are OK or not. Your choice. I think this is much cleaner than a drawn-out if statement.
I don't actually know what the efficiency of this is, but I saw this problem and wanted to solve it in a non-nested-if() style so more knowledgeable folk could compare it's relative efficiency. Soooooo... Here's and alternative way of going about it :)
function GetLetterForPercentGrade($grade)
{
$letter= chr(($grade >59) ? (10-floor($grade /10))+64 : 'F');
$sign = chr(abs((ceil(((($grade %10)*10)+1)/34)*34)-69)+10);
return $letter.$sign;
}
$grade=87;
$grades=array("A"=>range(95,100),"B"=>range(80,94),"C"=>range(70,79),"Failed"=>range(0,69));
foreach($grades as $g=>$v){
if ( in_array($grade,$v) ){
print $g."\n";
}
}
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;
}