Home > Backend Development > PHP Tutorial > PHP array introductory tutorial: Get the current array key and value

PHP array introductory tutorial: Get the current array key and value

WBOY
Release: 2016-07-25 08:57:58
Original
945 people have browsed it
This article introduces the method of obtaining the keys and values ​​​​of the current array in the PHP array. Friends in need can refer to it.

In PHP array functions, each() function returns the current key/value pair of input_array and advances the pointer one position.

The form is as follows: array each(array array)

The returned array contains four keys, key 0 and key contain the key name, and key 1 and value contain the corresponding data. If the pointer is at the end of the array before each() is executed, false is returned.

For example:

<?php
$fruits = array("apple", "banana", "orange", "pear");  
print_r ( each($fruits) );  
  
// Array ( [1] => apple [value] => apple [0] => 0 [key] => 0 )  
?>
Copy after login

each() is often used in conjunction with list() to iterate over an array.

Example, loop to output the entire array:

<?php
$fruits = array("apple", "banana", "orange", "pear");  
reset($fruits);  
  
while (list($key, $val) = each($fruits))  
{  
echo "$key => $val<br />";  
} //by bbs.it-home.org
  
// 0 => apple  
// 1 => banana  
// 2 => orange  
// 3 => pear  
?>
Copy after login

Since assigning one array to another array will reset the original array pointer, in the above example if we assign $fruits to another variable inside the loop, it will cause an infinite loop. This completes array traversal.



source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template