Lessons → PHP Basics → Lesson 7

Arrays

PHP
⏱ 20 min read📖 BeginnerNot completed

Arrays store multiple values in a single variable. They are one of the most used data structures in PHP — especially when working with database results in Laravel.

Indexed Arrays

PHP
<?php
$fruits = ["apple", "banana", "cherry"];

echo $fruits[0];  // apple
echo $fruits[1];  // banana
echo $fruits[2];  // cherry

// Add item
$fruits[] = "date";
// or
array_push($fruits, "elderberry");

echo count($fruits);  // 5
?>

Associative Arrays

Key-value pairs — like a dictionary or JSON object:

PHP
<?php
$user = [
    "name"  => "John Doe",
    "email" => "john@example.com",
    "age"   => 25,
    "city"  => "Tokyo"
];

echo $user["name"];   // John Doe
echo $user["email"];  // john@example.com

// Add / update
$user["phone"] = "090-1234-5678";
$user["age"] = 26;

// Remove
unset($user["city"]);
?>

Multidimensional Arrays

PHP
<?php
$users = [
    ["name" => "John",  "age" => 25],
    ["name" => "Jane",  "age" => 28],
    ["name" => "Suraj", "age" => 30],
];

// Access nested data
echo $users[0]["name"];  // John
echo $users[2]["age"];   // 30

// Loop through
foreach ($users as $user) {
    echo $user["name"] . ": " . $user["age"] . "\n";
}
?>

Useful Array Functions

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

// Sort
sort($numbers);          // [1, 1, 2, 3, 4, 5, 6, 9]
rsort($numbers);         // reverse sort

// Search
in_array(5, $numbers);   // true
array_search(5, $numbers); // returns index

// Slice & Splice
array_slice($numbers, 0, 3);  // first 3 items
array_splice($numbers, 2, 1); // remove 1 item at index 2

// Map, Filter, Reduce
$doubled = array_map(fn($n) => $n * 2, $numbers);
$evens   = array_filter($numbers, fn($n) => $n % 2 === 0);
$sum     = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);

// Merge
$a = [1, 2, 3];
$b = [4, 5, 6];
$merged = array_merge($a, $b);  // [1,2,3,4,5,6]
?>
💡
In Laravel, Eloquent returns Collections — which are supercharged arrays with methods like ->filter(), ->map(), ->where(), ->pluck() and many more.
← Previous Lesson Next Lesson →
🧠

Test your knowledge!

Take the PHP Basics quiz.

Take Quiz →