Working with Arrays in PHP and MySQL
- 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
When simple variables are just not good enough, arrays come into play (or objects, but that’s another topic). The array section in the PHP manual, available at http://php.net/array, lists approximately 80 functions that are helpful. Therefore, this book could be filled with array-related phrases alone. However, not all of these functions are really used often. Therefore, this chapter presents the most important problems you’ll have to solve when working with arrays—and, of course, solutions for these problems.
There are two types of arrays. The names they are given differ sometimes, but usually arrays are distinguished between numeric arrays and associative arrays. The first type of array uses numeric keys, whereas the latter type can also use strings as keys.
Creating an array can be done in one of three ways:
- Using the array() statement
$a = array('I', 'II', 'III', 'IV');
- Successively adding values to an array using the variable name and square brackets
$a[] = 'I'; $a[] = 'II'; $a[] = 'III'; $a[] = 'IV';
- Using a new square brackets syntax introduced in PHP 5.4
$a = ['I', 'II', 'III', 'IV'];
The latter method is probably the most intuitive one for Web developers because JavaScript features a very similar syntax. For the sake of backward compatibility, we will still use the first option throughout this chapter.
When using associative arrays, the same three methods can be used; however, this time keys and values must be provided:
$a1 = array('one' => 'I', 'two' => 'II', 'three' => 'III', 'four' => 'IV'); $a2['one'] = 'I'; $a2['two'] = 'II'; $a2['three'] = 'III'; $a2['four'] = 'IV'; $a1 = ['one' => 'I', 'two' => 'II', 'three' => 'III', 'four' => 'IV'];
Arrays can also be nested, when an array element itself is an array:
$a = array( 'Roman' => array('one' => 'I', 'two' => 'II', 'three' => 'III', 'four' => 'IV'), 'Arabic' => array('one' => '1', 'two' => '2', 'three' => '3', 'four' => '4') );
Now, the Arabic representation of the number four can be accessed using $a['Arabic']['four'].
Of course, arrays are not only created within a script but can also come from other sources, including from HTML forms (see Chapter 5, “Interacting with Web Forms”) and from cookies and sessions (see Chapter 6, “Remembering Users (Cookies and Sessions)”). But if the array is there, what’s next? The following phrases give some pointers.
Accessing All Elements of Numeric Arrays
foreach ($a as $element)
<?php $a = array('I', 'II', 'III', 'IV'); foreach ($a as $element) { echo htmlspecialchars($element) . '<br />'; } ?>
Looping through an Array with foreach (foreach-n.php)
Looping through numeric (or indexed) arrays can most easily be done using foreach because in each iteration of the loop, the current element in the array is automatically written in a variable, as shown in the preceding code.
Alternatively, a for loop can also be used. The first array element has the index 0; the number of array indices can be retrieved using the count() function:
<?php $a = array('I', 'II', 'III', 'IV'); for ($i = 0; $i < count($a); $i++) { echo htmlspecialchars($a[$i]) . '<br />'; } ?>
Looping through an Array with for (for-n.php)
Both ways are equally good (or bad); though, usually, using foreach is the much more convenient way. However, there is a third possibility: The PHP function each() returns the current element in an array. The return value of each() is an array, in which you can access the value using the numeric index 1, or the string index 'value'. Using a while loop, the whole array can be traversed. The following code once again prints all elements in the array, this time using each():
<?php $a = array('I', 'II', 'III', 'IV'); while ($element = each($a)) { echo htmlspecialchars($element['value']) . '<br />'; //or: $element[1] } ?>
Looping through an Array with each (each-n.php)
The output of the three listings is always the same, of course.