1024programmer PHP Complete list of PHP array traversal methods (foreach, list, each)_php skills-php tutorial

Complete list of PHP array traversal methods (foreach, list, each)_php skills-php tutorial

Arrays are divided into two categories in PHP: numerically indexed arrays and associative arrays.
The numeric index array is the same as the array in C language, the subscripts are 0, 1, 2…
The subscript of the associative array may be of any type, similar to hash, map and other structures in other languages.

The following introduces three methods of traversing associative arrays in PHP:

Method 1: foreach

The code is as follows:


<?php
$sports = array(
‘football’ => ‘good’,
‘swimming’ => ‘very well’,
‘running’ => ‘not good’);
foreach ($sports as $key => $value ) {
echo $key.”: “.$value.”
“;
?>


Output result:

football: good
swimming: very well
running: not good

Method 2: each

The code is as follows:


<?php
$sports = array(
‘football’ = > ‘good’,
‘swimming’ => ‘very well’,
‘running’ => ‘not good’);
while ($elem = each($sports)) {
echo $elem[‘key’].”: “.$elem[‘value’].”
“;
?>

Method 3: list & each

The code is as follows:


<?php
$sports = array(
‘football’ => ‘good’,
‘swimming’ => ‘very well’,
‘running’ = > ‘not good’);
while (list($key, $value) = each($sports)) {
echo $key.”: “.$value.”
“;
?>

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/complete-list-of-php-array-traversal-methods-foreach-list-each_php-skills-php-tutorial/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: 34331943@QQ.com

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索