Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

PHP Switch statement

Description

The control statement which allows us to make a decision from the number of choices is called a switch-case-default. It is almost similar to a series of if statements on the same expression.

Syntax:

switch (expression )
{
case constant1:
 execute the statement;
 break;
case constant2:
 execute the statement;
 break;
case constant3:
 execute the statement;
 break;
.........
default:
 execute the statement;
}

The expression following the keyword switch can be a variable or any other expression like an integer, a string, or a character. Each constant in  each case must be different from all others.

When we run a program containing the switch statement at first the expression following the keyword switch is evaluated. The value it gives is then matched one by one against the constant values that follow the case statements. When a match is found the program executes the statements following that case. If no match is found with any of the case statements, only the statements following the default are executed.  

Example:

In the following example $xint is equal to 3, therefore switch statement executes the third echo statement.

<?php
$xint=3;
switch($xint) {
case 1:
echo "This is case No 1.";
break;
case 2:
echo "This is case No 2.";
break;
case 3:
echo "This is case No 3.";
break;
case 4:
echo "This is case No 4.";
break;
default:
echo "This is default.";
}
?>

Output:

This is case No 3.

View the example in the browser

Pictorial presentation of switch loop

php-while-loop

 

Previous: continue statement
Next: declare statement



PHP: Tips of the Day

How to Sort Multi-dimensional Array by Value?

Try a usort, If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:

Example:

function sortByOrder($a, $b) {
    return $a['order'] - $b['order'];
}

usort($myArray, 'sortByOrder');

Starting in PHP 5.3, you can use an anonymous function:

usort($myArray, function($a, $b) {
    return $a['order'] - $b['order'];
});

And finally with PHP 7 you can use the spaceship operator:

usort($myArray, function($a, $b) {
    return $a['order'] <=> $b['order'];
});

To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero - best explained below. You can also use this for sorting on sub-elements.

usort($myArray, function($a, $b) {
    $retval = $a['order'] <=> $b['order'];
    if ($retval == 0) {
        $retval = $a['suborder'] <=> $b['suborder'];
        if ($retval == 0) {
            $retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
        }
    }
    return $retval;
});

If you need to retain key associations, use uasort() - see comparison of array sorting functions in the manual

Ref : https://bit.ly/3i77vCC