Home >Backend Development >PHP Problem >What are the commonly used methods for traversing arrays in PHP?

What are the commonly used methods for traversing arrays in PHP?

王林
王林forward
2019-09-03 16:08:182910browse

What are the commonly used methods for traversing arrays in PHP?

This article mainly introduces three common methods of traversing arrays in PHP, and analyzes PHP's use of for, foreach, list(), each() and while for arrays in the form of examples. Friends who need to use the related operation skills of traversing arrays can refer to it.

The most manipulated data in PHP is probably the array, which has the characteristics of high efficiency, fast speed and convenient storage.

There are three commonly used methods for traversing arrays in PHP:

1. The for loop is the most flexible in usage. It is so flexible that you doubt your life, but remember the format. very simple.
2. foreach is a function specially provided by PHP for array traversal. It was introduced in the PHP4 version and has the highest execution efficiency.
3. Use list(), each() and while loop in combination to traverse the array. This usage uses Less, but the list() function uses a lot

Instance:

<?php
$arr1 = array(&#39;http://www.jinsanguo.com/&#39;,&#39;金三国&#39;,&#39;PHP教程&#39;);
$num = count($arr1);//count()为数组统计函数
  for($i=0;$i<$num;++$i){
      echo $arr1[$i]."<br/>";
    }
echo "<hr/>";
$arr2 = array(&#39;http://www.jinsanguo.com/&#39;,&#39;金三国&#39;,&#39;PHP教程&#39;);
    foreach($arr2 as $value){
     echo $value."<br/>";
    }
echo "<hr/>";
$arr3 = array(&#39;http://www.jinsanguo.com/&#39;,&#39;金三国&#39;,&#39;PHP教程&#39;);
   while(list($key,$value) = each($arr3)){
     echo $key.&#39;=>&#39;.$value."<br/>";
  }
?>

Run result:

What are the commonly used methods for traversing arrays in PHP?

each()The function needs to pass an array as a parameter, return the key/value pair of the current element in the array, and move the array pointer backward to the position of the next element.

list() Function, this is not a real function, it is a language structure of PHP.

list()Assign values ​​to a group of variables in one step.

For more related questions, please visit the PHP Chinese website: PHP Video Tutorial

The above is the detailed content of What are the commonly used methods for traversing arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete