Arrays & Functions Lesson 9 of 17
PHP Arrays — Indexed, Associative and Multidimensional
Store lists and records in PHP arrays — indexed arrays, associative arrays with keys, arrays of arrays, adding, removing and checking items, and printing them with print_r.
PHP's array is incredibly flexible: it can be a simple list, a dictionary of key–value pairs, or a table of records. Data from forms and databases always arrives as arrays, so they're essential in PHP.
Indexed arrays
<?php
$subjects = ["Math", "Science", "English"];
$subjects[] = "Filipino"; // add to the end
echo $subjects[0], "\n";
echo count($subjects), "\n";
echo $subjects[count($subjects) - 1], "\n";
print_r($subjects);
Output
Math
4
Filipino
Array
(
[0] => Math
[1] => Science
[2] => English
[3] => Filipino
)Associative arrays
Instead of numbers, use meaningful keys:
<?php
$student = [
"name" => "Maria Clara",
"grade" => 10,
"section" => "Rizal",
];
echo $student["name"] . " - Grade " . $student["grade"], "\n";
$student["average"] = 94.5; // add a new key
$student["section"] = "Bonifacio"; // change a value
unset($student["grade"]); // remove a key
print_r($student);
Output
Maria Clara - Grade 10
Array
(
[name] => Maria Clara
[section] => Bonifacio
[average] => 94.5
)Arrays of arrays (records)
<?php
$products = [
["name" => "Pandesal", "price" => 25, "stock" => 40],
["name" => "Kape", "price" => 8, "stock" => 200],
["name" => "Itlog", "price" => 9, "stock" => 0],
];
foreach ($products as $p) {
$status = $p["stock"] > 0 ? "in stock" : "SOLD OUT";
echo str_pad($p["name"], 10) . "₱" . $p["price"] . " $status\n";
}
echo "Second product: " . $products[1]["name"];
Output
Pandesal ₱25 in stock Kape ₱8 in stock Itlog ₱9 SOLD OUT Second product: Kape
When you read rows from a database, you get exactly this shape: a list of associative arrays.
Checking arrays
<?php
$officers = ["Ana", "Ben", "Carla"];
$student = ["name" => "Dan", "grade" => 9];
var_dump(in_array("Ben", $officers));
var_dump(array_key_exists("grade", $student));
var_dump(isset($student["email"]));
echo array_search("Carla", $officers);
Output
bool(true) bool(true) bool(false) 2
Adding and removing
<?php
$queue = ["Ana", "Ben"];
array_push($queue, "Carla"); // add to end
array_unshift($queue, "Teacher"); // add to start
$first = array_shift($queue); // remove from start
$last = array_pop($queue); // remove from end
echo "$first, $last | " . implode(", ", $queue);
Output
Teacher, Carla | Ana, Ben
Destructuring
<?php
[$first, $second] = ["Gold", "Silver"];
["name" => $n, "grade" => $g] = ["name" => "Ana", "grade" => 9];
echo "$first $second | $n $g";
Output
Gold Silver | Ana 9
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04