✍️

PHP Arrays Explained with Examples and Programs

Mastering PHP Arrays

Mastering PHP Arrays: Real-Life Examples & Methods

If you’re writing PHP, there’s one data structure you simply cannot escape: Arrays. Whether you're handling form data, fetching database records, or building an API, arrays are the backbone of data manipulation in PHP. Let's break them down.

What is an Array in PHP?

Imagine you are moving to a new house. Instead of carrying one book at a time, you put them all into a cardboard box. You label the box "Books" and carry it all at once. In PHP, an array is that cardboard box. It’s a special variable that can hold multiple values under a single name.

<?php
// Without an array (The hard way)
$fruit1 = "Apple";
$fruit2 = "Banana";

// With an array (The smart way)
$fruits = ["Apple", "Banana", "Orange"];
?>

The 3 Types of PHP Arrays

Type 1

Indexed Arrays (The Numbered List)

An indexed array uses numeric indexes (starting from 0) to access the values.

Real-Life Example: A line of people at a ticket counter. The first person is number 0, the second is number 1, and so on.

<?php
$groceries = ["Milk", "Bread", "Eggs"];

// Accessing the first item (Indexes start at 0!)
echo $groceries[0]; // Output: Milk
?>
Type 2

Associative Arrays (The Labeled Drawer)

Associative arrays use named keys instead of numbers. You assign a specific label (key) to each value.

Real-Life Example: A contact list in your phone. You look up the name "John" to find his phone number.

<?php
$userProfile = [
    "name"  => "John Doe",
    "email" => "john@example.com",
    "age"   => 28
];

echo $userProfile["name"]; // Output: John Doe
?>
Type 3

Multidimensional Arrays (The Filing Cabinet)

A multidimensional array is an array that contains other arrays inside it.

Real-Life Example: An apartment building. The building is the main array. Each floor is a sub-array. Inside each floor are the apartments.

<?php
$company = [
    "Engineering" => [
        ["name" => "Alice", "role" => "Backend"],
        ["name" => "Bob", "role" => "Frontend"]
    ]
];

echo $company["Engineering"][0]["name"]; // Output: Alice
?>

Must-Know PHP Array Methods

PHP comes packed with built-in array functions that do the heavy lifting for you. Here are the essentials.

Searching

in_array()

Checks if a value exists. Real-life: Checking if someone is on the VIP list.

$vip = ["Alice", "Bob"];
if (in_array("Bob", $vip)) {
    echo "Welcome!";
}
Transforming

array_map()

Applies a function to every item. Real-life: Adding tax to all prices on a conveyor belt.

$prices = [10, 20];
$withTax = array_map(
    fn($p) => $p * 1.10, 
    $prices
);
// [11, 22]
Filtering

array_filter()

Keeps items that pass a test. Real-life: Quality control throwing away broken toys.

$scores = [45, 80, 55];
$passing = array_filter(
    $scores, 
    fn($s) => $s >= 60
);
// [80]
Combining

array_merge()

Combines two arrays into one. Real-life: Pouring two bags of candy into one bowl.

$arr1 = ["Apple"];
$arr2 = ["Banana"];
$combined = array_merge($arr1, $arr2);
// ["Apple", "Banana"]

Conclusion

Arrays are the workhorses of PHP. They take your code from rigid and repetitive to dynamic and scalable. By combining the different array types with PHP's powerful built-in methods, you can write clean, efficient, and highly readable code in just a few lines. Happy coding!

❮ Previous Next ❯