Real Use Cases of Arrays in PHP
Why This Lesson Focuses on Real Scenarios
Understanding array syntax and functions is one thing — recognizing when and why to reach for an array in real code is another. This lesson skips the basics (already covered in earlier lessons) and instead walks through practical, real-world situations where arrays are the natural solution, the way you'd actually encounter them while building an application.
Use Case 1: Handling Form Data
Every time a user submits an HTML form, PHP receives that data as an array through $_POST or $_GET, even for a single-field form.
php
<?php
// Assume a form submitted: name, email, and message fields
$formData = $_POST;
// $formData now looks something like:
// [
// "name" => "Rohan",
// "email" => "rohan@example.com",
// "message" => "Hello there"
// ]
$name = $formData['name'] ?? '';
$email = $formData['email'] ?? '';
if (empty($name) || empty($email)) {
echo "Please fill in all required fields.";
} else {
echo "Thank you, $name. We'll respond to $email shortly.";
}
Using the null coalescing operator (??) here protects against errors if a field wasn't submitted at all, which is a common defensive habit when working with form arrays.
Use Case 2: Building a Shopping Cart
An e-commerce cart is a textbook example of nested arrays — a list of items, where each item itself is an associative array of details.
php
<?php
$cart = [
["name" => "Laptop", "price" => 55000, "quantity" => 1],
["name" => "Mouse", "price" => 500, "quantity" => 2],
["name" => "Keyboard", "price" => 1200, "quantity" => 1],
];
$total = 0;
foreach ($cart as $item) {
$lineTotal = $item['price'] * $item['quantity'];
$total += $lineTotal;
echo $item['name'] . " x" . $item['quantity'] . " = Rs. " . $lineTotal . "\n";
}
echo "Total: Rs. " . $total;
This pattern, an array of associative arrays, is one of the most common data shapes you'll work with in real PHP applications, since it maps naturally to rows of data from a database.
Use Case 3: Filtering Data Based on Conditions
Real applications frequently need to show only a subset of data — active users, products in stock, orders above a certain value. The array_filter() function handles this cleanly.
php
<?php
$products = [
["name" => "Laptop", "price" => 55000, "inStock" => true],
["name" => "Old Phone", "price" => 8000, "inStock" => false],
["name" => "Keyboard", "price" => 1200, "inStock" => true],
];
$availableProducts = array_filter($products, function ($product) {
return $product['inStock'] === true;
});
foreach ($availableProducts as $product) {
echo $product['name'] . "\n";
}
// Output: Laptop, Keyboard (Old Phone is excluded)
This is significantly cleaner than manually looping through the array and checking each condition with an if statement inside a foreach, especially as filtering logic grows more complex.
Use Case 4: Sorting Data for Display
Displaying data in a meaningful order (cheapest first, most recent first, alphabetically) is a constant requirement, handled with functions like usort().
php
<?php
$products = [
["name" => "Keyboard", "price" => 1200],
["name" => "Laptop", "price" => 55000],
["name" => "Mouse", "price" => 500],
];
usort($products, function ($a, $b) {
return $a['price'] <=> $b['price']; // ascending order by price
});
foreach ($products as $product) {
echo $product['name'] . " - Rs. " . $product['price'] . "\n";
}
// Output: Mouse, Keyboard, Laptop
The <=> symbol is called the "spaceship operator," and it's a compact way to compare two values for sorting — it returns -1, 0, or 1 depending on whether the first value is less than, equal to, or greater than the second.
Use Case 5: Building Navigation Menus
Website navigation menus are almost always generated by looping through an array rather than hardcoding each link, since it keeps the structure easy to update in one place.
php
<?php
$menuItems = [
["label" => "Home", "url" => "/"],
["label" => "About", "url" => "/about"],
["label" => "Blog", "url" => "/blog"],
["label" => "Contact", "url" => "/contact"],
];
echo "<nav><ul>";
foreach ($menuItems as $item) {
echo "<li><a href='{$item['url']}'>{$item['label']}</a></li>";
}
echo "</ul></nav>";
Adding a new menu item later just means adding one line to the array, rather than editing HTML scattered throughout the codebase.
Use Case 6: Counting and Grouping Data
Arrays are frequently used to tally or group information, such as counting how many orders fall into each status category.
php
<?php
$orders = [
["id" => 1, "status" => "delivered"],
["id" => 2, "status" => "pending"],
["id" => 3, "status" => "delivered"],
["id" => 4, "status" => "cancelled"],
["id" => 5, "status" => "pending"],
];
$statusCounts = [];
foreach ($orders as $order) {
$status = $order['status'];
if (!isset($statusCounts[$status])) {
$statusCounts[$status] = 0;
}
$statusCounts[$status]++;
}
print_r($statusCounts);
// [ "delivered" => 2, "pending" => 2, "cancelled" => 1 ]
This grouping pattern shows up constantly in dashboards and reporting features, where raw data needs to be summarized before being displayed.
Use Case 7: Working with JSON Data (APIs)
Arrays and JSON are closely connected in PHP — most APIs send and receive data in JSON format, which PHP converts directly into arrays.
php
<?php
$jsonResponse = '{"name": "Rohan", "role": "Developer", "active": true}';
$userData = json_decode($jsonResponse, true); // true converts to an associative array
echo $userData['name']; // Rohan
echo $userData['role']; // Developer
// Converting back to JSON, e.g. to send as an API response
$outputJson = json_encode(["status" => "success", "user" => $userData]);
echo $outputJson;
Passing true as the second argument to json_decode() is important here — without it, PHP returns an object instead of an array, which requires different syntax (-> instead of []) to access.
Use Case 8: Validating Multiple Form Fields at Once
Rather than writing a separate if check for every required field, arrays let you loop through a list of required fields and validate them systematically.
php
<?php
$formData = ["name" => "Rohan", "email" => "", "phone" => "9876543210"];
$requiredFields = ["name", "email", "phone"];
$errors = [];
foreach ($requiredFields as $field) {
if (empty($formData[$field])) {
$errors[] = ucfirst($field) . " is required.";
}
}
if (!empty($errors)) {
foreach ($errors as $error) {
echo $error . "\n";
}
}
// Output: Email is required.
This approach scales well — adding a new required field just means adding one entry to the $requiredFields array, without duplicating validation logic.
Common Patterns at a Glance
Real-World Task Array Pattern Used ------------------------------------------------------------ Form submission Associative array ($_POST) Shopping cart Array of associative arrays Filtering visible items array_filter() Sorting for display usort() with <=> Navigation menus Looping over a simple list Grouping/counting data Associative array as a tally API data exchange json_decode() / json_encode() Multi-field validation Looping over required fields
What's Next
You've now seen arrays used the way they actually appear in real applications, not just in isolated syntax examples. With variables, control flow, functions, loops, and arrays all covered, you have the core foundation needed to start exploring object-oriented PHP, which is where the next chapter of this series begins.