π PHP Multidimensional Arrays
Multidimensional arrays are arrays that contain other arrays as their elements. These arrays can have two or more levels, but in practice, they seldom go beyond three levels. While multidimensional arrays can be numeric or associative, PHP most commonly uses associative arrays to organize data.
You can think of a two-dimensional (2D) array as a table. Each row is an array, and the columns are the individual elements in that array. This structure is useful when you want to organize related data, such as grouping information by category or type.
Creating Multidimensional Associative Arrays
To create a multidimensional associative array, start by building the individual row arrays. Then, you can nest those arrays within a larger array, as shown below:
<?php
$row1array = ["index1" => "value1", "index2" => "value2", "index3" => "value3"];
$row2array = ["index1" => "value1", "index2" => "value2", "index3" => "value3"];
$multiArray = [
"row1Index" => $row1array,
"row2Index" => $row2array
];
?>
Accessing Array Elements
To access elements in a multidimensional associative array, use the parent arrayβs key followed by the sub-array's key:
<?php
$value = $multiArray["row1Index"]["index2"];
// Retrieves the second value from the first row
?>
Using Loops
To retrieve multiple values from a multidimensional array, you can nest loops. For example:
<?php
$pets = [
"Dogs" => ["Rocky" => "Shepherd", "Butch" => "Beagle", "Buddy" => "Poodle"],
"Cats" => ["Kitty" => "Calico", "Daisy" => "Tabby", "Fluffy" => "Persian"],
"Rodents" => ["Cooper" => "Hamster", "Jerry" => "Gerbil", "Ratigan" => "Rat"]
];
foreach ($pets as $category => $animal) {
echo "<h1>My favorite $category are</h1>";
foreach ($animal as $name => $type) {
echo "<p>$name the $type</p>";
}
}
?>
<!-- HTML Output -->
<h1>My favorite Dogs are</h1>
<p>Rocky the Shepherd</p>
<p>Butch the Beagle</p>
<p>Buddy the Poodle</p>
<h1>My favorite Cats are</h1>
<p>Kitty the Calico</p>
<p>Daisy the Tabby</p>
<p>Fluffy the Persian</p>
<h1>My favorite Rodents are</h1>
<p>Cooper the Hamster</p>
<p>Jerry the Gerbil</p>
<p>Ratigan the Rat</p>
Creating Drop-Down Lists
Multidimensional arrays are also useful for generating dynamic HTML elements like drop-down lists. You can create a drop-down list by iterating over the array and building the HTML dynamically:
<?php
// Initialize the main structure of the dropdown with HEREDOC
$petList = <<<HTML
<br>
<select id="pets" name="pets">
<option value="">β Select Pet β</option>
HTML;
// Loop through the categories and pets, using escaped double quotes for clarity
foreach ($pets as $category => $animal) {
$petList .= "<optgroup label=\"$category\">";
foreach ($animal as $name => $type) {
$petList .= "<option value=\"$name\">$name the $type</option>";
}
$petList .= "</optgroup>";
}
// Close the select tag
$petList .= </select>;
echo $petList;
?>
This will output an HTML form with a select drop-down list of pets grouped by category:
<label for="pets">Choose a pet:</label><br>
<select id="pets" name="pets">
<option value="">β Select Pet β</option>
<optgroup label="Dogs">
<option value="Rocky">Rocky the Shepherd</option>
<option value="Butch">Butch the Beagle</option>
<option value="Buddy">Buddy the Poodle</option>
</optgroup>
<optgroup label="Cats">
<option value="Kitty">Kitty the Calico</option>
<option value="Daisy">Daisy the Tabby</option>
<option value="Fluffy">Fluffy the Persian</option>
</optgroup>
<optgroup label="Rodents">
<option value="Cooper">Cooper the Hamster</option>
<option value="Jerry">Jerry the Gerbil</option>
<option value="Ratigan">Ratigan the Rat</option>
</optgroup>
</select>
The final output will render in the browser as a drop down list.
Array Filters
To retrieve a group of values from the multidimensional associative array based on a specific criteria, add conditional statements that will filter the values you need.
<?php
/* Multidimensional array */
$pets = [
"Dogs" => ["Rocky" => "Shepherd", "Butch" => "Beagle", "Buddy" => "Poodle"],
"Cats" => ["Kitty" => "Calico", "Daisy" => "Tabby", "Fluffy" => "Persian"],
"Rodents" => ["Cooper" => "Hamster", "Jerry" => "Gerbil", "Ratigan" => "Rat"]
];
/* Nested foreach loops with conditional*/
foreach ($pets as $subArray => $pet) {
if ($subArray == "Cats") { // condition to limit output to Cats only
echo "<p>My favorite " . $subArray . " are<br>\n";
foreach ($pet as $name => $type) {
echo "$name the $type<br>\n";
}
echo "</p>\n";
}
}
?>
<!-- HTML Output only Cats-->
<p>My favorite Cats are<br>
Kitty the Calico<br>
Daisy the Tabby<br>
Fluffy the Persian<br>
</p>
Sorting Arrays
Sorting arrays is straightforward using PHP's built-in functions. Below are some common sorting functions:
- sort() - Sorts numeric arrays in ascending order.
- rsort() - Sorts numeric arrays in descending order.
- asort() - Sorts associative arrays by value in ascending order.
- ksort() - Sorts associative arrays by key in ascending order.
Here's an example of sorting a numeric array:
<?php
$numbers = [4, 6, 2, 22, 11];
sort($numbers);
?>
User-Defined Sort Functions
You can also define custom sorting logic using usort()
for indexed arrays or uasort()
for associative arrays. Hereβs how:
<?php
function customSort($a, $b) {
return ($a < $b) ? -1 : 1;
}
$numbers = [4, 6, 2, 22, 11];
usort($numbers, "customSort");
?>