PHP Arrays

Store multiple values in a single variable

📚 What are PHP Arrays?

Arrays are a fundamental data structure in PHP that allow you to store multiple values in a single variable. Instead of creating separate variables for each value, you can group related values together in an array. This makes your code more organized and efficient, especially when working with lists of data.


<?php
// Simple array example
$fruits = array("Apple", "Banana", "Orange");
echo $fruits[0]; // Apple
echo $fruits[1]; // Banana
?>
                                    

Output:

Apple

Banana

Types of Arrays

🔢

Indexed Arrays

Arrays with numeric indexes starting from 0. Perfect for ordered lists where position matters, like rankings or sequences.

<?php
$colors = ["Red", "Green", "Blue"];
echo $colors[0]; // Red
?>
🔑

Associative Arrays

Arrays with named keys instead of numbers. Use descriptive keys to access values, making code more readable and self-documenting.

<?php
$person = ["name" => "John", "age" => 25];
echo $person["name"]; // John
?>
🎯

Multidimensional Arrays

Arrays containing other arrays. Create complex data structures like tables, matrices, or nested lists for organizing hierarchical information.

<?php
$students = [
    ["Alice", 20],
    ["Bob", 22]
];
?>
🔄

Array Functions

PHP provides powerful built-in functions to manipulate arrays. Sort, search, filter, merge, and transform arrays with ease using these tools.

<?php
$nums = [3, 1, 2];
sort($nums);
print_r($nums); // [1, 2, 3]
?>

🔹 Creating Indexed Arrays

Indexed arrays are created using numeric indexes (starting from 0) to store multiple values in a single variable. This is useful when you have a collection of items where the order matters, such as a list of fruits or vegetables.

<?php
// Method 1: Using array() function
$fruits = array("Apple", "Banana", "Orange");

// Method 2: Using short syntax []
$vegetables = ["Carrot", "Potato", "Tomato"];

// Accessing elements
echo "First fruit: " . $fruits[0];
echo "<br>";
echo "Second vegetable: " . $vegetables[1];
?>

Output:

First fruit: Apple

Second vegetable: Potato

🔹 Associative Arrays

Use named keys to access array values:

<?php
// Create associative array
$student = array(
    "name" => "Alice",
    "age" => 20,
    "grade" => "A"
);

// Access values using keys
echo "Name: " . $student["name"];
echo "<br>";
echo "Age: " . $student["age"];
echo "<br>";
echo "Grade: " . $student["grade"];
?>

Output:

Name: Alice

Age: 20

Grade: A

🔹 Looping Through Arrays

Looping through arrays allows you to access and process each element individually. PHP provides two main ways to loop through arrays: using a for loop or a foreach loop.

<?php
$colors = ["Red", "Green", "Blue", "Yellow"];

// Using for loop
echo "Using for loop:<br>";
for($i = 0; $i < count($colors); $i++) {
    echo $colors[$i] . "<br>";
}

echo "<br>Using foreach loop:<br>";
// Using foreach loop (easier)
foreach($colors as $color) {
    echo $color . "<br>";
}
?>

Output:

Using for loop:

Red

Green

Blue

Yellow


Using foreach loop:

Red

Green

Blue

Yellow

🔹 Looping Associative Arrays

To process associative arrays, you can loop through them and access both the key (name) and value for each element. This is useful when you want to display or work with both the property names and their corresponding values.

<?php
$person = [
    "name" => "John",
    "age" => 25,
    "city" => "New York"
];

foreach($person as $key => $value) {
    echo "$key: $value<br>";
}
?>

Output:

name: John

age: 25

city: New York

🔹 Multidimensional Arrays

Arrays containing other arrays:

<?php
$students = [
    ["Alice", 20, "A"],
    ["Bob", 22, "B"],
    ["Charlie", 21, "A"]
];

// Access elements
echo "First student: " . $students[0][0];
echo "<br>";
echo "Bob's grade: " . $students[1][2];

echo "<br><br>All students:<br>";
foreach($students as $student) {
    echo $student[0] . " (Age: " . $student[1] . ", Grade: " . $student[2] . ")<br>";
}
?>

Output:

First student: Alice

Bob's grade: B


All students:

Alice (Age: 20, Grade: A)

Bob (Age: 22, Grade: B)

Charlie (Age: 21, Grade: A)

🔹 Common Array Functions

PHP provides many useful array functions:

<?php
$numbers = [3, 1, 4, 1, 5, 9, 2];

// Count elements
echo "Count: " . count($numbers);
echo "<br>";

// Sort array
sort($numbers);
echo "Sorted: " . implode(", ", $numbers);
echo "<br>";

// Add element to end
array_push($numbers, 10);
echo "After push: " . implode(", ", $numbers);
echo "<br>";

// Check if value exists
if(in_array(5, $numbers)) {
    echo "5 is in the array";
}
?>

Output:

Count: 7

Sorted: 1, 1, 2, 3, 4, 5, 9

After push: 1, 1, 2, 3, 4, 5, 9, 10

5 is in the array

🔹 Array Manipulation

Add, remove, and modify array elements:

<?php
$fruits = ["Apple", "Banana"];

// Add to end
$fruits[] = "Orange";
echo "Added Orange: " . implode(", ", $fruits);
echo "<br>";

// Remove last element
array_pop($fruits);
echo "After pop: " . implode(", ", $fruits);
echo "<br>";

// Add to beginning
array_unshift($fruits, "Mango");
echo "Added Mango at start: " . implode(", ", $fruits);
echo "<br>";

// Remove first element
array_shift($fruits);
echo "After shift: " . implode(", ", $fruits);
?>

Output:

Added Orange: Apple, Banana, Orange

After pop: Apple, Banana

Added Mango at start: Mango, Apple, Banana

After shift: Apple, Banana

🔹 Practical Example

Create a simple shopping cart using arrays:

<?php
$cart = [
    ["name" => "Laptop", "price" => 999, "qty" => 1],
    ["name" => "Mouse", "price" => 25, "qty" => 2],
    ["name" => "Keyboard", "price" => 75, "qty" => 1]
];

$total = 0;
echo "Shopping Cart:<br><br>";

foreach($cart as $item) {
    $subtotal = $item["price"] * $item["qty"];
    $total += $subtotal;
    echo $item["name"] . " - $" . $item["price"] . " × " . $item["qty"] . " = $" . $subtotal . "<br>";
}

echo "<br><strong>Total: $" . $total . "</strong>";
?>

Output:

Shopping Cart:


Laptop - $999 × 1 = $999

Mouse - $25 × 2 = $50

Keyboard - $75 × 1 = $75


Total: $1124

💡 Array Tips:

  • Use foreach: Easiest way to loop through arrays
  • count(): Get the number of elements in an array
  • in_array(): Check if a value exists in an array
  • implode(): Convert array to string
  • explode(): Convert string to array

🧠 Test Your Knowledge

What is the index of the first element in a PHP array?