In the previous article "PHP quickly implements deletion of special characters such as spaces, tabs, and newlines (two methods)", I introduced how to delete spaces, tabs, and other special characters. Interested friends can learn about special characters such as line breaks~
So the focus of this article is to teach you how to loop associative arrays?
First of all, let’s briefly introduce what is an associative array in PHP?
Associative arrays are arrays using specified keys that you assign to the array.
There are two methods of creating associative arrays in PHP:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or
$age['Peter']="35"; $age['Ben']="37"; $age['Joe']="43";
Let’s look directly at the two methods of looping through associative arrays:
First method:
Note: In an associative array, elements are defined in the form of key/value pairs; when using an associative array and want to access it The keys are also relevant when all data is included; for this, the foreach()
loop must also provide variable names for the elements' keys, not just their values.
The PHP code is as follows:
<?php $a = array('One' => '猫猫', 'Two' => '狗狗', 'Three' =>'大象', 'Four' => '兔子'); foreach ($a as $key => $value) { echo $key.' : '. $value.'<br/>'; }
The output result is:
One : 猫猫 Two : 狗狗 Three : 大象 Four : 兔子
Second method:
Note: It is not feasible to use a for loop to iterate through all array elements. However, it is possible to use a combination of each()
and while
; the important point is that the key name can be retrieved using index 0 or the string index 'key'.
PHP code is as follows:
<?php $a = array('One' => '猫猫', 'Two' => '狗狗', 'Three' =>'大象', 'Four' => '兔子'); while ($element = each($a)) { echo htmlspecialchars($element['key'] . ': ' .$element['value']) . '<br/>'; }
Output result:
One: 猫猫 Two: 狗狗 Three: 大象 Four: 兔子
PHP Chinese website platform has a lot of video teaching resources, everyone is welcome to learn "PHP Video Tutorial》!
The above is the detailed content of How to loop through associative arrays in PHP (two ways). For more information, please follow other related articles on the PHP Chinese website!