Php loop statement usage

Source: Internet
Author: User

Today is the last two articles on basic PHP knowledge. The goal is to give you a preliminary understanding of PHP. This article mainly describes the PHP loop, which is used to execute the same code block for a specified number of times. Save time for our development.
Loop

When writing code, you often need to run the same code block multiple times. You can use loop statements in the code to complete this task.

In PHP, we can use the following loop statement:

While
The code block is executed cyclically as long as the specified condition is true.
Do... While
Execute a code block first, and then repeat the loop when the specified condition is set.
For
Number of times the code block is executed cyclically
Foreach
Loop code blocks based on each element in the array

While statement

As long as the specified condition is true, the while statement repeats the code block.
Syntax
While (condition)
Code to be executed;
Example

The following example demonstrates a loop. As long as the variable I is less than or equal to 5, the code will continue to run cyclically. Every cycle of a loop increases by 1:

The code is as follows: Copy code

<Html>
<Body>

<? Php
$ I = 1;
While ($ I <= 5)
  {
Echo "The number is". $ I. "<br/> ";
$ I ++;
  }
?>

</Body>
</Html>


Do... While statement

Do... The while statement will execute the code at least once-then, as long as the condition is true, the loop will be repeated.
Syntax
Do
 {
Code to be executed;
 }
While (condition );
Example

In the following example, the I value is accumulated once. Then, as long as the I is less than 5, it will continue to accumulate:

The code is as follows: Copy code

<Html>
<Body>

<? Php
$ I = 0;
Do
  {
$ I ++;
Echo "The number is". $ I. "<br/> ";
  }
While ($ I <5 );
?>

</Body>
</Html>


For statement

If you have determined the number of times the code block is repeated, you can use the for statement.
Syntax
For (initialization; condition; increment)
 {
Code to be executed;
4}

Note: the for statement has three parameters. The first parameter initializes the variable, the second parameter saves the condition, and the third parameter contains the increment required for the execution cycle. If the initialization or increment parameter contains multiple variables, separate them with commas. The condition must be calculated as true or false.
Example

The following example shows the text "Hello World !" Shown 5 times:

The code is as follows: Copy code

<Html>
<Body>

<? Php
For ($ I = 1; $ I <= 5; $ I ++)
{
Echo "Hello World! <Br/> ";
}
?>

</Body>
</Html>

Foreach statement

The foreach statement is used to traverse arrays cyclically.

For each loop, the value of the current array element is assigned to the value variable (the array pointer is moved one by one), and so on.
Syntax
Foreach (array as value)
 {
Code to be executed;
 }

Example

The following example demonstrates a loop that outputs the value of a given array:

The code is as follows: Copy code

<Html>
<Body>

<? Php
$ Arr = array ("one", "two", "three ");

Foreach ($ arr as $ value)
{
Echo "Value:". $ value. "<br/> ";
}
?>

</Body>
</Html>

A Directory Traversal function

The code is as follows: Copy code
<? Php
/*
* Recursively retrieve all files in the specified path or files that match the specified regular expression (excluding "." and "."), and return results in array form
* @ Param string $ dir
* @ Param string [$ pattern]
* @ Return array
*/
Function file_list ($ dir, $ pattern = "")
{  
$ Arr = array ();
$ Dir_handle = opendir ($ dir );
If ($ dir_handle)
    {  
// This must be strictly compared because the returned file name may be "0"
While ($ file = readdir ($ dir_handle ))! = False)
        {  
If ($ file = '.' | $ file = '..')
            {  
Continue;
            }  
$ Tmp = realpath ($ dir. '/'. $ file );
If (is_dir ($ tmp ))
            {  
$ RetArr = file_list ($ tmp, $ pattern );
If (! Emptyempty ($ retArr ))
                {  
$ Arr [] = $ retArr;
                }  
            }  
Else
            {  
If ($ pattern = "" | preg_match ($ pattern, $ tmp ))
                {  
$ Arr [] = $ tmp;
                }  
            }  
        }  
Closedir ($ dir_handle );
    }  
Return $ arr;
}  
  
// List all files ending with the ". php" extension (case insensitive) in the root directory of the website
Echo '<pre> ';
Print_r (file_list ($ _ SERVER ['document _ root'], "//. php $/I "));
Echo '</pre> ';
?>

This allows for convenient infinite directory traversal ..

 

Performance Comparison between foreach and while


If the array "read" operation is performed in a loop, foreach is faster than while:

If the array "write" operation is performed in a loop, while is faster than foreach

The code is as follows: Copy code

/**
* Performance Comparison Between while and foreach functions
 *
*/
 
// Foreach function
Foreach ($ array as $ key => $ value ){
Echo $ array [$ key] = $ value .'...';
}
 
// While function
While (list ($ key) = each ($ array )){
$ Array [$ key] = $ array [$ key]. '...';
}

Conclusion: foreach is generally considered to be slower than while when it involves value replication, but in fact, if it is just to read the array in a loop, foreach is very
This is because PHP adopts the replication mechanism of "reference count, write copy". That is to say, even if a variable is copied in PHP, the initial form is basically
It is still the form of reference. Only when the content of the variable changes will the real replication occur. The reason for doing so is to save memory consumption and improve
Replication efficiency.

 


In this case, foreach's efficient read operations are not difficult to understand. In addition, since foreach is not suitable for array write operations, we can get a knot
In most cases, code for array write operations like foreach ($ array as $ key => $ value) should be replaced with while (list ($ key) =
Each ($ array )). The speed difference produced by these skills may not be obvious in small projects, but in large projects like frameworks, a single request may involve a few
Hundreds of thousands of array loop operations, the difference will be significantly magnified.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.