Web Development /PHP Programming / Lesson
Web Development

Arrays

Learn how PHP arrays store collections of values, including indexed, associative and multidimensional arrays, and how to create, access, update, sort, search, filter, map, reduce and iterate over array data.

🎯

Learning Objectives

["Explain what arrays are and why they are useful in PHP programming.","Create and access indexed arrays using numeric keys.","Create and work with associative arrays using named keys.","Create and access multidimensional arrays.","Add, update and remove array elements safely.","Use foreach and other iteration techniques to process array data.","Use common PHP array functions for sorting, searching, filtering and transforming data.","Understand array keys, values, counting and membership checks.","Use array destructuring, spread syntax and useful modern PHP array features.","Apply arrays to practical tasks such as student records, product lists, filtering and data processing."]

📖

Lesson Content

Introduction to PHP Arrays

An array is a data structure that allows PHP to store multiple values in a single variable.

Instead of creating separate variables for every student, product, score, or category, an array allows related values to be grouped together.

<?php

$students = [
    "Daniel",
    "Grace",
    "Michael",
    "Sarah"
];

?>

Arrays are used extensively in PHP applications because websites and web applications constantly work with collections of data.

Examples of Data Commonly Stored in Arrays

  • Student names
  • Product lists
  • User records
  • Database results
  • Website navigation items
  • Categories
  • Configuration settings
  • API responses
  • Form data

1. Creating an Indexed Array

An indexed array uses numeric keys to identify its elements.

<?php

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

?>

By default, PHP assigns indexes beginning with 0.

IndexValue
0Blue
1Green
2Red
3Yellow

2. Accessing Array Elements

Use the element’s key inside square brackets to access a value.

<?php

$colors = [
    "Blue",
    "Green",
    "Red"
];

echo $colors[0];
echo $colors[2];

?>

The first value is accessed using index 0, while the third value is accessed using index 2.

3. Updating Array Elements

An existing array element can be changed by assigning a new value to its key.

<?php

$colors = [
    "Blue",
    "Green",
    "Red"
];

$colors[1] = "Orange";

print_r($colors);

?>

4. Adding Elements to an Array

The short array append syntax [] can add a new element to the end of an indexed array.

<?php

$students = [
    "Daniel",
    "Grace"
];

$students[] = "Michael";
$students[] = "Sarah";

print_r($students);

?>

PHP automatically assigns the next available integer key.

5. Using array_push()

The array_push() function can also add one or more values to the end of an array.

<?php

$students = [
    "Daniel",
    "Grace"
];

array_push(
    $students,
    "Michael",
    "Sarah"
);

print_r($students);

?>

For simply adding values to the end of an array, $array[] = $value is often shorter and clearer.

6. Removing Array Elements

The unset() function removes an element.

<?php

$students = [
    "Daniel",
    "Grace",
    "Michael"
];

unset($students[1]);

print_r($students);

?>

When an indexed element is removed using unset(), the remaining numeric keys are not automatically reindexed.

7. Reindexing an Array

The array_values() function can create a new array with sequential numeric indexes.

<?php

$students = [
    "Daniel",
    "Grace",
    "Michael"
];

unset($students[1]);

$students = array_values($students);

print_r($students);

?>

8. Counting Array Elements

The count() function returns the number of elements in an array.

<?php

$students = [
    "Daniel",
    "Grace",
    "Michael"
];

echo count($students);

?>

9. Looping Through an Indexed Array

A foreach loop is one of the easiest ways to process array values.

<?php

$students = [
    "Daniel",
    "Grace",
    "Michael"
];

foreach ($students as $student) {
    echo $student . "<br>";
}

?>

10. Accessing Keys and Values

The foreach loop can provide both the key and the value.

<?php

$students = [
    "Daniel",
    "Grace",
    "Michael"
];

foreach ($students as $index => $student) {
    echo $index . ": " . $student . "<br>";
}

?>

11. Associative Arrays

An associative array uses named keys instead of automatically assigned numeric keys.

<?php

$student = [
    "name" => "Daniel",
    "course" => "Web Development",
    "level" => 200
];

?>

Associative arrays are useful when values have meaningful labels.

12. Accessing Associative Array Values

<?php

$student = [
    "name" => "Daniel",
    "course" => "Web Development",
    "level" => 200
];

echo $student["name"];
echo $student["course"];
echo $student["level"];

?>

13. Updating Associative Arrays

<?php

$student = [
    "name" => "Daniel",
    "course" => "Web Development"
];

$student["course"] = "Data Analysis";

print_r($student);

?>

14. Adding Associative Array Elements

<?php

$student = [
    "name" => "Daniel"
];

$student["email"] = "daniel@example.com";

print_r($student);

?>

15. Looping Through an Associative Array

<?php

$student = [
    "name" => "Daniel",
    "course" => "Web Development",
    "level" => 200
];

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

?>

16. Checking Whether a Key Exists

The array_key_exists() function checks whether a specific key exists.

<?php

$student = [
    "name" => "Daniel",
    "course" => "Web Development"
];

if (array_key_exists("course", $student)) {
    echo "Course information exists.";
}

?>

17. Checking Whether a Value Exists

The in_array() function checks whether a value exists in an array.

<?php

$courses = [
    "Web Development",
    "Data Analysis",
    "Cyber Security"
];

if (in_array("Data Analysis", $courses, true)) {
    echo "Course found.";
}

?>

The third argument true enables strict comparison.

18. Multidimensional Arrays

A multidimensional array contains other arrays as its elements.

<?php

$students = [
    [
        "name" => "Daniel",
        "course" => "Web Development"
    ],
    [
        "name" => "Grace",
        "course" => "Data Analysis"
    ]
];

?>

This structure is useful when representing multiple records.

19. Accessing Multidimensional Arrays

<?php

$students = [
    [
        "name" => "Daniel",
        "course" => "Web Development"
    ],
    [
        "name" => "Grace",
        "course" => "Data Analysis"
    ]
];

echo $students[0]["name"];
echo $students[1]["course"];

?>

20. Looping Through Multidimensional Arrays

<?php

$students = [
    [
        "name" => "Daniel",
        "course" => "Web Development"
    ],
    [
        "name" => "Grace",
        "course" => "Data Analysis"
    ]
];

foreach ($students as $student) {
    echo $student["name"] . " - ";
    echo $student["course"] . "<br>";
}

?>

21. Sorting Indexed Arrays

PHP provides several functions for sorting arrays.

The sort() function sorts values in ascending order and reindexes numeric keys.

<?php

$courses = [
    "Web Development",
    "Cyber Security",
    "Data Analysis",
    "Graphics Design"
];

sort($courses);

print_r($courses);

?>

22. Reverse Sorting

The rsort() function sorts an indexed array in descending order.

<?php

$scores = [65, 90, 75, 82];

rsort($scores);

print_r($scores);

?>

23. Sorting Associative Arrays by Value

The asort() function sorts an associative array by value while preserving the keys.

<?php

$scores = [
    "Daniel" => 75,
    "Grace" => 90,
    "Michael" => 65
];

asort($scores);

print_r($scores);

?>

24. Sorting Associative Arrays by Key

The ksort() function sorts an associative array by its keys.

<?php

$students = [
    "Daniel" => 75,
    "Grace" => 90,
    "Michael" => 65
];

ksort($students);

print_r($students);

?>

25. array_keys()

The array_keys() function returns the keys of an array.

<?php

$student = [
    "name" => "Daniel",
    "course" => "Web Development",
    "level" => 200
];

$keys = array_keys($student);

print_r($keys);

?>

26. array_values()

The array_values() function returns the values of an array.

<?php

$student = [
    "name" => "Daniel",
    "course" => "Web Development",
    "level" => 200
];

$values = array_values($student);

print_r($values);

?>

27. Searching for a Value

The array_search() function searches for a value and returns its key when found.

<?php

$courses = [
    "Web Development",
    "Data Analysis",
    "Cyber Security"
];

$key = array_search(
    "Data Analysis",
    $courses,
    true
);

if ($key !== false) {
    echo "Course found at index: " . $key;
}

?>

Use strict comparison when checking the result because a valid array key can be 0.

28. Filtering Arrays

The array_filter() function creates an array containing values that pass a condition.

<?php

$scores = [35, 55, 70, 82, 40];

$passed = array_filter(
    $scores,
    fn($score) => $score >= 50
);

print_r($passed);

?>

29. Transforming Arrays with array_map()

The array_map() function applies a callback to every element.

<?php

$scores = [10, 20, 30, 40];

$doubled = array_map(
    fn($score) => $score * 2,
    $scores
);

print_r($doubled);

?>

30. Reducing Arrays with array_reduce()

The array_reduce() function combines array values into a single result.

<?php

$numbers = [10, 20, 30, 40];

$total = array_reduce(
    $numbers,
    fn($carry, $number) => $carry + $number,
    0
);

echo $total;

?>

31. Combining Arrays

The array_merge() function combines arrays.

<?php

$frontend = [
    "HTML",
    "CSS"
];

$programming = [
    "JavaScript",
    "PHP"
];

$skills = array_merge(
    $frontend,
    $programming
);

print_r($skills);

?>

32. Spread Operator

Modern PHP supports the spread operator for unpacking arrays into another array.

<?php

$frontend = [
    "HTML",
    "CSS"
];

$backend = [
    "PHP",
    "MySQL"
];

$skills = [
    ...$frontend,
    ...$backend
];

print_r($skills);

?>

33. Removing Duplicate Values

The array_unique() function removes duplicate values.

<?php

$courses = [
    "PHP",
    "JavaScript",
    "PHP",
    "CSS"
];

$uniqueCourses = array_unique($courses);

print_r($uniqueCourses);

?>

34. Converting Arrays to Strings

The implode() function joins array values into a string.

<?php

$skills = [
    "HTML",
    "CSS",
    "JavaScript",
    "PHP"
];

echo implode(", ", $skills);

?>

35. Converting Strings to Arrays

The explode() function splits a string into an array.

<?php

$skills = "HTML,CSS,JavaScript,PHP";

$list = explode(",", $skills);

print_r($list);

?>

36. Extracting Array Data

PHP provides list() and array destructuring for assigning array elements to variables.

<?php

$student = [
    "Daniel",
    "Web Development",
    200
];

[$name, $course, $level] = $student;

echo $name;
echo $course;
echo $level;

?>

37. Associative Array Destructuring

<?php

$student = [
    "name" => "Daniel",
    "course" => "Web Development",
    "level" => 200
];

[
    "name" => $name,
    "course" => $course,
    "level" => $level
] = $student;

echo $name;
echo $course;
echo $level;

?>

38. Null Coalescing with Arrays

The null coalescing operator ?? is useful when reading optional array keys.

<?php

$student = [
    "name" => "Daniel"
];

$email = $student["email"] ?? "No email provided";

echo $email;

?>

This prevents an undefined-key warning when the key does not exist.

39. Array Data from Forms

HTML forms can submit multiple values using array-style field names.

<form method="post">
    <input type="text" name="student[name]">
    <input type="text" name="student[course]">
    <button type="submit">Submit</button>
</form>

PHP can receive these values as an array through $_POST["student"]. Form input should always be validated and sanitized appropriately before being used.

40. Arrays and Database Results

Database queries commonly return rows as arrays. For example, an application may process multiple student records using a loop.

<?php

$students = [
    [
        "name" => "Daniel",
        "course" => "Web Development"
    ],
    [
        "name" => "Grace",
        "course" => "Cyber Security"
    ]
];

foreach ($students as $student) {
    echo $student["name"] . "<br>";
}

?>

When working with actual database queries, always use the database API’s recommended prepared-query methods and validate the resulting data before displaying it.

41. Practical Example: Student Records

<?php

$students = [
    [
        "name" => "Daniel",
        "course" => "Web Development",
        "score" => 78
    ],
    [
        "name" => "Grace",
        "course" => "Data Analysis",
        "score" => 86
    ],
    [
        "name" => "Michael",
        "course" => "Cyber Security",
        "score" => 69
    ]
];

foreach ($students as $student) {
    echo "Name: " . $student["name"] . "<br>";
    echo "Course: " . $student["course"] . "<br>";
    echo "Score: " . $student["score"] . "<hr>";
}

?>

42. Practical Example: Filter Students

<?php

$students = [
    [
        "name" => "Daniel",
        "score" => 78
    ],
    [
        "name" => "Grace",
        "score" => 86
    ],
    [
        "name" => "Michael",
        "score" => 39
    ]
];

$passedStudents = array_filter(
    $students,
    fn($student) => $student["score"] >= 50
);

print_r($passedStudents);

?>

43. Practical Example: Product Prices

<?php

$prices = [
    1500,
    2500,
    3500,
    5000
];

$total = array_sum($prices);

$average = $total / count($prices);

echo "Total: " . $total . "<br>";
echo "Average: " . $average;

?>

44. Practical Example: Product Discount

<?php

$prices = [
    10000,
    15000,
    20000
];

$discountedPrices = array_map(
    fn($price) => $price * 0.9,
    $prices
);

print_r($discountedPrices);

?>

45. Nested Arrays

Arrays can contain arrays at multiple levels.

<?php

$academy = [
    "web_development" => [
        "HTML",
        "CSS",
        "JavaScript",
        "PHP"
    ],
    "data_analysis" => [
        "Excel",
        "SQL",
        "Python"
    ]
];

echo $academy["web_development"][2];

?>

46. Checking Whether an Array Is Empty

The empty() function can be used to check whether an array contains no usable value.

<?php

$students = [];

if (empty($students)) {
    echo "No students found.";
}

?>

When working with arrays, choose the appropriate check based on whether you need to distinguish between an empty array, a missing key, or a specific value.

47. Array Functions Worth Learning

PHP contains many useful array functions. Important examples include:

  • count()
  • array_push()
  • array_pop()
  • array_shift()
  • array_unshift()
  • array_merge()
  • array_unique()
  • array_keys()
  • array_values()
  • array_search()
  • in_array()
  • array_filter()
  • array_map()
  • array_reduce()
  • sort()
  • rsort()
  • asort()
  • arsort()
  • ksort()
  • krsort()
  • implode()
  • explode()

48. Arrays and Performance

Arrays are powerful, but developers should choose suitable data structures and operations for the amount of data being processed.

For large datasets, repeatedly copying or transforming very large arrays can consume significant memory. Database filtering, pagination, or more appropriate data structures may sometimes be preferable.

49. Common Array Mistakes

  • Accessing a key that does not exist without checking for it.
  • Assuming numeric indexes always remain sequential after using unset().
  • Using loose comparisons when strict comparison is required.
  • Confusing array keys with array values.
  • Modifying an array while unexpectedly relying on its original indexes.
  • Assuming database data always has the expected structure.
  • Displaying untrusted array data without appropriate output escaping.

50. Best Practices for PHP Arrays

  • Use descriptive associative keys.
  • Choose indexed arrays for ordered lists and associative arrays for named data.
  • Use foreach when readability is more important than manually managing indexes.
  • Use strict comparison where appropriate.
  • Check optional keys with isset(), array_key_exists(), or ?? depending on the requirement.
  • Use built-in array functions instead of unnecessarily rewriting common operations.
  • Keep multidimensional structures organized and predictable.
  • Validate external data before processing it.
  • Escape data appropriately when outputting it into HTML.

Lesson Summary

PHP arrays allow developers to store and process collections of values. The three major patterns introduced in this lesson are indexed arrays, associative arrays, and multidimensional arrays.

PHP provides a large collection of functions for sorting, searching, filtering, transforming, combining, and reducing arrays.

Understanding arrays is essential for working with forms, databases, APIs, configuration data, student records, product catalogs, and almost every data-driven PHP application.

💻

Code Example

<?php

$students = [
    [
        'name'   => 'Daniel',
        'course' => 'Web Development',
        'score'  => 78,
    ],
    [
        'name'   => 'Grace',
        'course' => 'Data Analysis',
        'score'  => 86,
    ],
    [
        'name'   => 'Michael',
        'course' => 'Cyber Security',
        'score'  => 39,
    ],
];

$passedStudents = array_filter(
    $students,
    fn(array $student): bool => $student['score'] >= 50
);

$studentNames = array_map(
    fn(array $student): string => $student['name'],
    $passedStudents
);

foreach ($passedStudents as $student) {
    echo $student['name'] . ' - ';
    echo $student['course'] . ' - ';
    echo $student['score'] . PHP_EOL;
}

echo PHP_EOL;
echo 'Passed students: ' . count($passedStudents) . PHP_EOL;

print_r($studentNames);
⭐

Key Takeaways

["An array stores multiple related values in one variable.","Indexed arrays use numeric keys, normally beginning at zero.","Associative arrays use meaningful named keys.","Multidimensional arrays contain other arrays and are useful for structured records.","Array elements can be accessed, updated, added, and removed using their keys.","foreach is one of the most readable ways to iterate through arrays.","PHP provides many built-in functions for sorting, searching, filtering, mapping, and reducing arrays.","Use strict comparisons when the distinction between different PHP types matters.","The null coalescing operator is useful for safely reading optional array values.","Array destructuring and the spread operator provide concise modern syntax for working with arrays.","Arrays are commonly used to represent form data, database results, API responses, and application records.","Good array design keeps data structured, predictable, validated, and easy to process."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress