Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional switch statements in PHP

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.

like image 857
Cyclone Avatar asked Oct 18 '11 00:10

Cyclone


People also ask

What are conditional statements of PHP?

In PHP we have the following conditional statements: if statement - executes some code if one condition is true. if...else statement - executes some code if a condition is true and another code if that condition is false. if...elseif...else statement - executes different codes for more than two conditions.

Can you use conditionals in switch statement?

The JavaScript switch keyword is used to create multiple conditional statements, allowing you to execute different code blocks based on different conditions.

What is switch conditional?

switch is a type of conditional statement that will evaluate an expression against multiple possible cases and execute one or more blocks of code based on matching cases. The switch statement is closely related to a conditional statement containing many else if blocks, and they can often be used interchangeably.

What is the difference between switch statement and conditional statement?

In the case of 'if-else' statement, either the 'if' block or the 'else' block will be executed based on the condition. In the case of the 'switch' statement, one case after another will be executed until the break keyword is not found, or the default statement is executed.


1 Answers

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

?>
like image 137
Aurelio De Rosa Avatar answered Sep 17 '22 14:09

Aurelio De Rosa