Conditional switch statements in PHP
Asked Answered
A

5

24

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.

Alunite answered 18/10, 2011 at 0:30 Comment(2)
You'll have to use if-elseif-else. PHP doesn't support this syntax.Chondro
Only scalar values allowed for cases.Incognito
B
51

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;
}

?>
Botulin answered 18/10, 2011 at 0:37 Comment(5)
@BoltClock: What does the true do?Alunite
And can I use floats here in the boolean expressions safely?Alunite
@Alunite Yes, you can use float too.Botulin
@Alunite super old but true in the switch tells the switch to always run. Its like a while (true) {...}Dworman
It's not different from a regular switch statement really. true is just a value, just like a variable holds a value. A switch just checks the cases to find the first one that has that same specified value.Jamnes
B
2

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.

Borchert answered 18/10, 2011 at 0:59 Comment(0)
O
2

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.
Omdurman answered 22/2, 2021 at 19:11 Comment(0)
G
1

PHP supports switch statements. Is that what you wanted?

Garnettgarnette answered 18/10, 2011 at 0:38 Comment(1)
No, I know normal switch seconds.Alunite
A
1

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";
}
Allegedly answered 13/10, 2022 at 13:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.