Related links:
PHP syntax(1): Basics and variables
PHP syntax(2): Data types, operators and functions
PHP syntax(3): Control structure (For Loop/If/Switch/While)
In this article, I will summarize a few commonly used control structures in PHP. Let’s start with the most special foreach. The rest of the control structures are similar to other languages, so this issue will be relatively simple.
Foreach Loop
Iterates through each element in the array and loops the block of code.
Usage: foreach ( $array as $value )
Every time a loop iteration is performed, the value of the current array element will be assigned to the $value variable, and the array pointer will move one by one until it reaches the last array element .
<code> $age=array("Bill"=>"35","Steve"=>"37","Peter"=>"43"); foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; }</code>
For loop
The basic for loop is as follows:
<code> for ($x=0; $x<=10; $x++) { echo "数字是:$x"; } </code>
If judgment
if has no special usage.
<code>if (条件) { 条件为 true 时执行的代码; } elseif (condition) { 条件为 true 时执行的代码; } else { 条件为 false 时执行的代码; }</code>
Switch
switch is also similar to C++.
<code>switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; default: echo "No number between 1 and 3"; }</code>
While
<code>while (条件为真) { 要执行的代码; }</code>
Do while
do...while loop first executes the code block once, then checks the condition, and repeats the loop if the specified condition is true.
<code>do { 要执行的代码; } while (条件为真);</code>
Finally
I look back on the past few days of starting the blog, and I also saw the "Why not share" articles written by other bloggers in the garden, and I have a lot of thoughts. In fact, there are still many people who are willing to share, but there are too many reasons for not sharing. Lack of time, laziness, and fear of being laughed at are all factors. Originally, I could finish reading PHP Grammar in an hour, but if I want to compile it into a blog article, I have to think about a lot of things. Just writing a basic article will take me a few nights, which is really a mixed blessing.
Now that I think about the people who can insist on blogging every day, it’s really not easy. I salute you! I hope I can spare more than three days a week to
write a blog. The above introduces PHP syntax three: control structure For loop/If/Switch/While, including blogging and PHP syntax. I hope it will be helpful to friends who are interested in PHP tutorials.