PHP development basic tutorial if else statement
1. PHP conditional statements
are used to perform different actions according to different conditions
In future study and work, it is often necessary to perform different actions for different judgments. Actions. We can use conditional statements in our code to accomplish this task.
In PHP, the following conditional statements are provided:
if statement - execute code when the condition is true
if ...else statement - executes a block of code when a condition is true, and executes another block of code when the condition is not true
if...else if....else statement - among several conditions Execute a block of code when one is true
switch statement - execute a block of code when one of several conditions is true
2. If statement
The if statement is used to execute code only when the specified condition is true.
The syntax is:
If (condition){
The code to be executed when the condition is true;
}
Example:
<?php //定義應(yīng)該變量 $score = 61; if($score>60){ echo "恭喜你,及格了"; } ?>
Note: There is no semicolon after the "}" sign in this structure
##3. If...else statement
If the requirement becomes to execute a piece of code when the condition is true, and to execute another piece of code when the condition is not true, you need to use the if...else statement. The syntax is: if (condition){
Code executed when the condition is true;
}
else
{
If the condition is not true The code that is executed when;
}
<?php //取1-10之間的一個(gè)隨機(jī)整數(shù) $x=rand(1,10); //判斷整數(shù)是否大于等于4 if($x>=4){ echo "恭喜你,中大獎(jiǎng)了"; }else{ echo "很遺憾,再來一次吧"; } ?>You have a 70% chance of winning, come and try it now
4. if...else if....else statement
Now the need is to execute a code block when one of several conditions is true, please use if...else if. ..else statement. Syntax: if (condition){
if code executed when the condition is true;
}
else if (condition)
{
elseif Code executed when the condition is established;
}
else
{
Code executed when the condition is not established;
}
<?php //取1-10之間的一個(gè)隨機(jī)整數(shù) $x=rand(1,10); //判斷整數(shù)是否在指定的范圍內(nèi) if($x>=9){ echo "恭喜你,中了一等獎(jiǎng)"; }else if($x>=7){ echo "恭喜你,中了二等獎(jiǎng)"; }else if($x>=4){ echo "恭喜你,中了二等獎(jiǎng)"; }else{ echo "很遺憾,再來一次吧"; } ?>There are four kinds of output results. You can try it yourself to see the output. ResultNote: There can be spaces or no spaces between if else
5. Switch statement
The switch statement will be in the next Chapter explanation