Home  >  Article  >  Backend Development  >  PHP traverses the array foreach each() list() method summary

PHP traverses the array foreach each() list() method summary

WBOY
WBOYOriginal
2016-07-25 08:56:191228browse
  1. foreach($array as $value){ //$array is the array to be traversed, $value is the pointer pointing to the current value of the array, as plays the role of assignment
  2.   code to executed;
  3. }
Copy The code

foreach statement can also get the key name of the array, as follows:

  1. foreach($array as $key => $value){
  2.   echo $key "-" $value. "
    ";
  3. }
Copy code

two , echo() function The function of each() is to split the key-value pairs of the current element of the array into a new array, and use the next element as the current element. For example, the 'Robert'=>'Bob' key-value pair in Array(...,'Robert'=>'Bob',...) is split into Array([1]=>'Bob',[value] =>'Bob',[0]=>'Robert',[key]=>'Robert') array, split into two sets (a total of four key-value pairs) to return, the serial number pairs of 0 and 1, key and value name-value pairs, just use one of them.

Example:

  1. $prices=Array('Tries' => 100, 'Oil' => 10, 'Spank Plugs' => 4);
  2. while($elements = each( $prices)){
  3.  echo $elements['key']; //echo $elements[0];
  4.  echo " - ";
  5.  echo $elements['value']; //echo $element[1];
  6. echo "
    ";
  7. }
Copy code

output result: Tires-100 Oil-10 Spank Plugs-4

Three, the list() function traverses the array The list() function can be used to decompose an array into a series of values. list() is often used together with each(). But list() can also be used without each(), for example: list($key, $value) = explode(":", $v); list($key, $value) = each($array); //$key, $value can be named arbitrarily. This sentence assigns the current elements at positions 0 and 1 of the array returned by each to the $key and $value variables. example:

  1. $prices=Array('Tries' => 100, 'Oil' => 10, 'Spank Plugs' => 4);
  2. while(list($product, $prices) = each($prices);){
  3.  echo $product "-" $prices;
  4.  echo "
    ";
  5. }
Copy code

Output result: Tires-100 Oil-10 Spank Plugs-4

Another implementation method:

  1. $prices=Array('Tries' => 100, 'Oil' => 10, 'Spank Plugs' => 4);
  2. list($product, $price ) = $each($prices);
  3. echo "$product - $price"; //Output the first array
  4. $next = $next($prices); //Move the pointer back
  5. echo $next;
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn