What Are We Doing in This Post?
So far every variable we created stored exactly one value. One name, one price, one score.
But real applications deal with collections. A list of products. A set of user details. A group of orders. Storing each one in a separate variable would be chaos.
Arrays solve this. An array is a single variable that holds multiple values. This is one of the most important data structures in PHP and you will use arrays in literally every project you ever build.
What is an Array?
Real world analogy: Think of an array like a train. A train has multiple compartments and each compartment holds passengers. The train itself has one name, but it carries many things inside it. A variable holds the train's name. An array is the train — one name, many compartments.
<?php
$colors = ["Red", "Green", "Blue", "Yellow"];
print_r($colors);
?>
Output:
Array ( [0] => Red [1] => Green [2] => Blue [3] => Yellow )
print_r is a built-in PHP function that displays the full contents of an array in a readable format. We use it constantly while working with arrays.
Notice the numbers 0, 1, 2, 3 next to each value. These are called indexes. PHP automatically assigns a numeric index to each item starting from 0, not 1. This is called zero-based indexing and it is standard across almost all programming languages.
Accessing Array Items
To access a specific item from an array, you use its index inside square brackets.
<?php
$colors = ["Red", "Green", "Blue", "Yellow"];
echo $colors[0]; echo "<br>"; echo $colors[2]; echo "<br>"; echo $colors[3];
?>
Output:
Red Blue Yellow
$colors[0] gives you the first item. $colors[2] gives you the third item. Remember — counting starts at zero.
Modifying and Adding Items
<?php
$colors = ["Red", "Green", "Blue"];
$colors[1] = "Purple";
$colors[] = "Orange";
print_r($colors);
?>
Output:
Array ( [0] => Red [1] => Purple [2] => Blue [3] => Orange )
Assigning to an existing index overwrites that value. Green became Purple at index 1.
Using empty square brackets $colors[] = adds a new item at the end of the array automatically. PHP figures out the next available index on its own.
Associative Arrays — Arrays With Named Keys
An indexed array uses numbers as keys. An associative array lets you define your own meaningful key names.
Real world analogy: An indexed array is like a numbered locker in a gym — locker 1, locker 2, locker 3. An associative array is like a hotel room with a name tag — "Presidential Suite", "Deluxe Room", "Standard Room." The name tells you exactly what is inside.
<?php
$user = [ "name" => "Gagan", "email" => "gagan@gmail.com", "age" => 22, "city" => "Delhi", "is_premium" => true ];
echo $user["name"]; echo "<br>"; echo $user["email"]; echo "<br>"; echo $user["age"];
?>
Output:
Gagan gagan@gmail.com 22
The => symbol maps a key to a value. To access a value you use its key name inside square brackets. This is far more readable than remembering that index 0 is name and index 3 is city.
Associative arrays are how you will represent a single record from a database in PHP. When Laravel fetches a user from the database, it comes back as an associative array or object with named fields exactly like this.
Multidimensional Arrays — Arrays Inside Arrays
A multidimensional array is an array where each item is itself an array. This lets you represent structured data like a table.
Real world analogy: Think of a spreadsheet. The spreadsheet is the outer array. Each row is an inner array. Each cell in a row is a value.
<?php
$students = [ ["name" => "Gagan", "score" => 88, "grade" => "B"], ["name" => "Rahul", "score" => 95, "grade" => "A"], ["name" => "Priya", "score" => 72, "grade" => "C"], ["name" => "Anjali", "score" => 60, "grade" => "C"], ];
foreach ($students as $student) { echo $student["name"] . " — Score: " . $student["score"] . " — Grade: " . $student["grade"]; echo "<br>"; }
?>
Output:
Gagan — Score: 88 — Grade: B Rahul — Score: 95 — Grade: A Priya — Score: 72 — Grade: C Anjali — Score: 60 — Grade: C
This structure is almost identical to what you get when you fetch multiple rows from a database. Each row is an associative array. All rows together form a multidimensional array. Learning to think in this structure now will make database work in Laravel feel completely natural.
To access a specific cell directly:
<?php
echo $students[1]["name"];
?>
Output: Rahul
$students[1] gets the second student (index 1). ["name"] gets the name field from that student's array.
Built-in Array Functions
PHP gives you a rich set of built-in functions for working with arrays. Here are the most important ones.
count — how many items are in the array:
<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"]; echo count($fruits);
?>
Output: 4
Real world use: displaying "Showing 4 of 20 products" on a listing page.
array_push and array_pop — add and remove from the end:
<?php
$cart = ["Keyboard", "Mouse"];
array_push($cart, "Monitor"); print_r($cart); echo "<br>";
array_pop($cart); print_r($cart);
?>
Output:
Array ( [0] => Keyboard [1] => Mouse [2] => Monitor ) Array ( [0] => Keyboard [1] => Mouse )
array_push adds one or more items to the end. array_pop removes the last item. Real world use: managing a shopping cart — add items, remove the last added item.
array_shift and array_unshift — remove and add from the beginning:
<?php
$queue = ["Person A", "Person B", "Person C"];
array_shift($queue); print_r($queue); echo "<br>";
array_unshift($queue, "Person Z"); print_r($queue);
?>
Output:
Array ( [0] => Person B [1] => Person C ) Array ( [0] => Person Z [1] => Person B [2] => Person C )
array_shift removes the first item. array_unshift adds a new item to the beginning. Real world use: managing a queue system where the first person in line gets served first.
in_array — check if a value exists:
<?php
$allowed_roles = ["admin", "editor", "moderator"]; $user_role = "editor";
if (in_array($user_role, $allowed_roles)) { echo "Access granted."; } else { echo "Access denied."; }
?>
Output: Access granted.
Real world use: permission and role checking systems. Does this user have a role that allows them to access this page?
array_search — find the key of a value:
<?php
$cities = ["Mumbai", "Delhi", "Bangalore", "Chennai"]; $key = array_search("Bangalore", $cities); echo $key;
?>
Output: 2
Returns the index of the found value. Returns false if not found.
sort and rsort — sort indexed arrays:
<?php
$scores = [45, 92, 67, 23, 88];
sort($scores); print_r($scores); echo "<br>";
rsort($scores); print_r($scores);
?>
Output:
Array ( [0] => 23 [1] => 45 [2] => 67 [3] => 88 [4] => 92 ) Array ( [0] => 92 [1] => 88 [2] => 67 [3] => 45 [4] => 23 )
sort sorts ascending. rsort sorts descending.
ksort and asort — sort associative arrays:
<?php
$prices = ["Monitor" => 15000, "Keyboard" => 2500, "Mouse" => 800];
asort($prices); print_r($prices);
?>
Output:
Array ( [Mouse] => 800 [Keyboard] => 2500 [Monitor] => 15000 )
asort sorts by value while keeping key-value pairs intact. ksort sorts by key alphabetically.
array_merge — combine two arrays:
<?php
$electronics = ["Laptop", "Phone"]; $accessories = ["Case", "Charger", "Cable"];
$all_products = array_merge($electronics, $accessories); print_r($all_products);
?>
Output:
Array ( [0] => Laptop [1] => Phone [2] => Case [3] => Charger [4] => Cable )
array_unique — remove duplicate values:
<?php
$tags = ["php", "laravel", "php", "web", "laravel", "backend"]; $unique_tags = array_unique($tags); print_r($unique_tags);
?>
Output:
Array ( [0] => php [1] => laravel [3] => web [5] => backend )
Duplicates removed. Real world use: cleaning up tag lists or category selections where users may submit duplicates.
array_slice — extract a portion of an array:
<?php
$products = ["A", "B", "C", "D", "E", "F", "G"]; $page_one = array_slice($products, 0, 3); $page_two = array_slice($products, 3, 3);
print_r($page_one); echo "<br>"; print_r($page_two);
?>
Output:
Array ( [0] => A [1] => B [2] => C ) Array ( [0] => D [1] => E [2] => F )
Real world use: pagination. Show 3 items per page. Page one gets items 0 to 2. Page two gets items 3 to 5.
A Real World Example — Shopping Cart System
Let us build a simple shopping cart using everything from this episode.
Create cart.php in your phplearning folder:
<!DOCTYPE html> <html> <head> <title>Shopping Cart</title> </head> <body>
<?php
$cart = [ ["name" => "Wireless Mouse", "price" => 599, "qty" => 2], ["name" => "Mechanical Keyboard", "price" => 2499, "qty" => 1], ["name" => "USB Hub", "price" => 899, "qty" => 3], ];
$total = 0;
echo "<h2>Your Cart</h2>"; echo "<table border='1' cellpadding='8'>"; echo "<tr><th>Product</th><th>Price</th><th>Qty</th><th>Subtotal</th></tr>";
foreach ($cart as $item) { $subtotal = $item["price"] * $item["qty"]; $total += $subtotal;
echo "<tr>";
echo "<td>" . $item["name"] . "</td>";
echo "<td>Rs. " . $item["price"] . "</td>";
echo "<td>" . $item["qty"] . "</td>";
echo "<td>Rs. " . $subtotal . "</td>";
echo "</tr>";
}
echo "</table>"; echo "<h3>Total Items: " . count($cart) . "</h3>"; echo "<h3>Grand Total: Rs. $total</h3>";
$discount = ($total > 3000) ? "10% discount applied!" : "No discount available."; echo "<p>$discount</p>";
?>
</body> </html>
Visit http://localhost:8080/phplearning/cart.php
You will see a proper cart table with product names, prices, quantities, subtotals, a grand total, and a discount message that appears automatically when the total crosses Rs. 3000.
This combines multidimensional arrays, foreach loops, arithmetic operators, the ternary operator, and string output — everything from the last four episodes working together as one complete feature.
What Did We Learn in This Post?
Arrays store multiple values in a single variable. Indexed arrays use numeric keys starting from 0. Associative arrays use custom named keys defined with =>.
Multidimensional arrays store arrays inside arrays — this mirrors how database rows look when fetched in PHP and Laravel.
Essential array functions: count, array_push, array_pop, array_shift, array_unshift, in_array, array_search, sort, rsort, asort, array_merge, array_unique, and array_slice.
Arrays, loops, and conditionals work together as the foundation of almost every dynamic feature in a real web application.
What is Coming in Episode 08?
Next we cover functions — how to write reusable blocks of code that you can call anywhere in your application.
Functions are how you stop repeating yourself. Instead of writing the same logic in ten different places, you write it once as a function and call it wherever you need it. Episode 08 covers defining functions, parameters, return values, default arguments, and variable scope.
See you in the next one.
Next Episode: Functions — Writing Reusable Code in PHP
This is Episode 07 of the PHP and Laravel — Zero to Hero series.
No comments:
Post a Comment