PHP Switch statement


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.


switch (expression )
case constant1:
 execute the statement;
case constant2:
 execute the statement;
case constant3:
 execute the statement;
 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.  


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

switch($xint) {
case 1:
echo "This is case No 1.";
case 2:
echo "This is case No 2.";
case 3:
echo "This is case No 3.";
case 4:
echo "This is case No 4.";
echo "This is default.";


This is case No 3.

View the example in the browser

Pictorial presentation of switch loop



Previous: continue statement
Next: declare statement

PHP: Tips of the Day

PHP: Convert one date format into another in PHP

The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.

You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-s format.

PHP 5.3 and up

Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates with.

PHP 5.2 and lower

You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.

But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands any date input short of the next time joe will slip on the ice. for example, this works:

$old_date = date('l, F d y h:i:s');         // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('Y-m-d H:i:s', $old_date_timestamp);

Ref : https://bit.ly/33QzKPG