Home > Backend Development > PHP Problem > How to display day of the week using PHP switch

How to display day of the week using PHP switch

藏色散人
Release: 2023-03-12 06:50:01
Original
3201 people have browsed it

I believe everyone knows that there is a very powerful function in PHP, which is the date function. Then you can easily get the day of the week through the date function. But as the title says, this article will introduce to you how to display the day of the week through PHP switch. Friends who are interested should not miss it~

Similarly, we will introduce the problem in detail: how to write a program and use The switch/case statement displays the day of the week based on a number (for example: Monday).

The question is very clear and the answer is easy to implement:

The PHP code is as follows:

<?php
$day = "2";

switch ($day) {
    case "1":
        echo "是星期一!";
        break;
    case "2":
        echo "是星期二!";
        break;
    case "3":
        echo "是星期三!";
        break;
    case "4":
        echo "是星期四!";
        break;
    case "5":
        echo "是星期五!";
        break;
    case "6":
        echo "是星期六!";
        break;
    case "7":
        echo "是星期日!";
        break;
    default:
        echo "无效数字!";
}
Copy after login

The number we give here is 2, so the result The output is:

是星期二!
Copy after login

For the above code, we pass 1 to 7 numbers in switch, day 1 will be considered as Monday, if the number is not between 1 to 7, invalid number will be displayed by default.

Note:

In PHP, the switch statement is used to perform different actions based on different conditions. You can use the Switch statement to selectively execute one of several code blocks.

Use the Switch statement to avoid lengthy if..elseif..else code blocks.

Grammar

switch (expression)
{
case label1:
  expression = label1 时执行的代码 ;
  break;  
case label2:
  expression = label2 时执行的代码 ;
  break;
default:
  表达式的值不等于 label1 及 label2 时执行的代码;
}
Copy after login

Working principle:

对表达式(通常是变量)进行一次计算
把表达式的值与结构中 case 的值进行比较
如果存在匹配,则执行与 case 关联的代码
代码执行后,break 语句阻止代码跳入下一个 case 中继续执行
如果没有 case 为真,则使用 default 语句
Copy after login

Finally, I would like to recommend the latest and most comprehensive "PHP Video Tutorial"~ Come and learn!

The above is the detailed content of How to display day of the week using PHP switch. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template