- Accessing All Elements of Numeric Arrays
- Accessing All Elements of Associative Arrays
- Accessing All Array Elements in Nested Arrays
- Turning an Array into Variables
- Converting Strings to Arrays
- Converting Arrays to Strings
- Sorting Arrays Alphabetically
- Sorting Associative Arrays Alphabetically
- Sorting Nested Arrays
- Sorting Nested Associative Arrays
- Sorting IP Addresses (as a Human Would)
- Sorting Anything
- Sorting with Foreign Languages
- Applying an Effect to All Array Elements
- Filtering Arrays
- Getting Random Elements Out of Arrays
- Making Objects Behave Like Arrays
Accessing All Elements of Associative Arrays
foreach ($a as $key => $value)
<?php $a = array('one' => 'I', 'two' => 'II', 'three' => 'III', 'four' => 'IV'); foreach ($a as $key => $value) { echo htmlspecialchars("$key: $value") . '<br />'; } ?>
Looping through an Associative Array with foreach (foreach-a.php)
When using an associative array and wanting to access all data in it, the keys are also of relevance. For this, the foreach loop can also provide a variable name for the element’s key, not only for its value.
Using count() is possible: count() returns the number of values in the array, not the number of elements. Looping through all array elements with for is not feasible. However, the combination of each() and while can be used, as shown in the following code. The important point is that the key name can be retrieved either using the index 0 or the string index 'key':
<?php $a = array('one' => 'I', 'two' => 'II', 'three' => 'III', 'four' => 'IV'); while ($element = each($a)) { echo htmlspecialchars($element['key'] . ': ' . $element['value']) . '<br />'; //or: $element[0] / $element[1] } ?>
Looping through an Associative Array with each (each-a.php)