wordpress CMS主题 微信
Home > 网站建设 > PHP array traversal methods

PHP array traversal methods

高时银博客 网站建设 点击: 2,086 次 0 0

In PHP, how to traverse the array? Is it right? With C language, using a for loop to iterate over? The answer is: no.. In PHP, method of traversing arrays than in the C language is much more simple. Method for traversing arrays in PHP mainly has the following 2.

1, the foreach circulation method.

This is the most used in PHP array traversal.

Syntax structure: foreach (array as $value) or foreach (array as $key=>$value)

Array arrays are represented here, $key represents an array of keys, $valuevalue. To have a look through the example below:

$a=array(1,199,"abd",9);foreach($a as $key=> $value){echo "\$a[".$key."]=".$value."<br>";


The output results:


The following example is a two dimensional array:

$a=array(array("two"=>3,3),array("five"=>"hao",1));foreach($a as $key=> $value){foreach($value as $k=>$v)


echo "\$a[".$key."][".$k."]=".$v."<br>";



The output results:


Note: if a 2D array also contain other elements, such as: $a=array (2, array,"one" ("=>3,3 two", "love"), array ("Five" = > "Hao", 1)) the blue character elements. Use foreach traversal of will.

2, while (list ($key, $value) =each (array)) cyclic traversal method.

We look at the examples:



echo "\$a[".$key."][".$k."]:".$v."<br>";



The output results:


Here we use the list () function and each () function. Each (array) returns onearray, as the following example:

$a=array ("=>3,3 two", "Five" = "Hao"); print_r (each ($a));

Results: Array ([1] = 3 [value] = > 3 [0] = > two [key] = > two)

While the list () function can be used to receive the each () function in the keyand key, and only accept each () function returns the number keys in the array.Through the while to scan the array, the each () function will continue to return a new array, and the list () function will continue to receive. Reach the traversal of the objective.


The difference between foreach and while traversal traversal is: an array of"read" operation using the foreach speed, obvious effect of large data; for an array of "write" operation using the while speed.

版权所有 © 转载时必须以链接形式注明作者和原始出处!