Arrays in PHP (Indexed, Associative, Multidimensional) with Real-World Examples

Congratulations!  You’ve mastered variables and functions. But what if you need to store multiple values in a single variable? Enter arrays—the Swiss Army knife of PHP data structures! 

In this guide, we’ll break down arrays in PHP in a fun and easy way with real-world examples

What is an Array?

An array is a special variable that holds multiple values in one place. Think of it as a magic box where each item has a numbered slot or a name tag!

$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Output: Apple

 Saves space – No need to create multiple variables.  Organized – Easily access data by index or key. Flexible – Store different types of values.

Types of Arrays in PHP 

PHP has three types of arrays: Indexed Arrays – Use numeric indexes (starting from 0). Associative Arrays – Use custom keys (like a dictionary). Multidimensional Arrays – Arrays inside arrays (like a matrix).

Let's explore each type! 

Indexed Arrays

The simplest type of array, where elements are indexed with numbers starting from 0.

Creating an Indexed Array

$colors = ["Red", "Green", "Blue"];
echo $colors[1]; // Output: Green

Adding Elements

$colors[] = "Yellow";
print_r($colors); 
// Output: Array ( [0] => Red [1] => Green [2] => Blue [3] => Yellow )

Looping Through an Indexed Array

foreach ($colors as $color) {
  echo $color . " ";
}
// Output: Red Green Blue Yellow

Associative Arrays 

Instead of numbers, keys are used to access values (like a dictionary).

Creating an Associative Array

$ages = ["Alice" => 25, "Bob" => 30, "Charlie" => 35];
echo $ages["Bob"]; // Output: 30

Adding Elements 

$ages["David"] = 40;
print_r($ages);
// Output: Array ( [Alice] => 25 [Bob] => 30 [Charlie] => 35 [David] => 40 )

Looping Through an Associative Array

foreach ($ages as $name => $age) {
  echo "$name is $age years old. ";
}
// Output: Alice is 25 years old. Bob is 30 years old. ...

Multidimensional Arrays

Arrays inside arrays! Used for tables, grids, or structured data.

Creating a Multidimensional Array

$students = [
  ["name" => "Alice", "age" => 25, "grade" => "A"],
  ["name" => "Bob", "age" => 30, "grade" => "B"],
  ["name" => "Charlie", "age" => 35, "grade" => "C"]
];

echo $students[1]["name"]; // Output: Bob

Looping Through a Multidimensional Array 

foreach ($students as $student) {
  echo $student["name"] . " is " . $student["age"] . " years old and got grade " . $student["grade"] . ". ";
}
// Output: Alice is 25 years old and got grade A. Bob is 30 years old...

Real-World Examples

Example 1: Shopping Cart 

$cart = [
  ["item" => "Laptop", "price" => 1000, "qty" => 1],
  ["item" => "Mouse", "price" => 50, "qty" => 2],
  ["item" => "Keyboard", "price" => 75, "qty" => 1]
];

echo "Total Price: ";
$total = 0;
foreach ($cart as $product) {
  $total += $product["price"] * $product["qty"];
}
echo "$total"; // Output: Total Price: 1175

Useful for e-commerce platforms!

Example 2: Student Grades

$grades = ["Alice" => 85, "Bob" => 90, "Charlie" => 78];
arsort($grades); // Sorts from highest to lowest
foreach ($grades as $student => $score) {
  echo "$student: $score ";
}

Perfect for school management systems!

Example 3: API Data Handling

$json = '{"name": "Alice", "age": 25, "city": "New York"}';
$data = json_decode($json, true);
echo $data["name"]; // Output: Alice

Essential for working with JSON responses!

Useful Array Functions 

PHP has tons of built-in array functions. Here are some must-knows:

Function Description
count($arr) Count number of elements
array_push($arr, $value) Add element at the end
array_pop($arr) Remove last element
array_shift($arr) Remove first element
array_unshift($arr, $value) Add element at the beginning
array_keys($arr) Get all keys
array_values($arr) Get all values
array_merge($arr1, $arr2) Combine arrays
in_array("value", $arr) Check if value exists

Example:

$nums = [10, 20, 30, 40];
if (in_array(20, $nums)) {
  echo "20 is in the array!";
}
// Output: 20 is in the array!

Arrays make your PHP code organized, efficient, and powerful. Now, you can:  Use indexed, associative, and multidimensional arrays.  Loop through arrays easily.  Store and manipulate structured data.  Apply arrays to real-world projects like shopping carts and APIs.

Post a Comment

0 Comments