Home > Backend Development > PHP Problem > The difference between if and switch in php

The difference between if and switch in php

(*-*)浩
Release: 2023-02-23 22:26:02
Original
4802 people have browsed it

The difference between if and switch in php

When the value being judged is a constant (fixed value), the operating efficiency of switch is higher than that of ifelse; (recommended learning: PHP Programming from Beginner to Master)

$status=3;   // 变判断的值为常量
switch($status){
  case 1:
    echo '常量值为1';
    break;   // 跳出循环
  case 2:
    echo '常量值为2';
    break;
  case 3:
    echo '常量值为3';
    break;
}
Copy after login

When the judged value is a variable, the operating efficiency of ifelse is higher than that of switch. Ifelse implements the policy of judging to the end and will start judging from the first condition , until the last else, so it is beneficial to learn to use switch;

$a = $_GET['a']; // 通过get传值后接值; 被判断的值
if($a=1){
  echo '变量a的值为1';
}elseif($a=2){
  echo '变量a的值为2';
}elseif($a=3){
  echo '变量a的值为3';
}else{
  echo '变量a的值为不知道';
}
Copy after login

PS: ifelse and switch can also be used for single-condition judgment, but ifelse is suitable for multi-condition judgment and switch is not applicable.

$a = $_GET['a']; // 通过get传值后接值; 被判断的值
if(!empty($a) && $a=1){
  echo '变量a的值为1';
}elseif(!empty($a) && $a=2){
  echo '变量a的值为2';
}elseif(!empty($a) && $a=3){
  echo '变量a的值为3';
}else{
  echo '变量a的值为不知道';
}
Copy after login

The above is the detailed content of The difference between if and switch in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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