This article analyzes the efficiency differences and applicability of switch and ifelse in PHP with examples. Share it with everyone for your reference. The specific analysis is as follows:
These two methods in PHP are used to determine whether the value meets the conditions, and take different actions if it does/does not meet the conditions.
No matter what language you write a program in, you must consider the running efficiency of the code. After consulting some information, switch and ifelse each have superior efficiency in different 'environments'.
1. When the value being judged is a constant (fixed value), the operating efficiency of switch is higher than that of ifelse;
$changliang=3; // 变判断的值为常量 switch($changliang){ case 1: echo '常量值为1'; break; // 跳出循环 case 2: echo '常量值为2'; break; case 3: echo '常量值为3'; break; }
2. When the judged value is a variable, the operating efficiency of ifelse is higher than that of switch. Ifelse implements the policy of judging from the first condition to 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的值为不知道'; }
I hope this article will be helpful to everyone’s PHP programming design.