PHP for the Web·PHP from first script to a working app

Arrays and loops

Indexed and associative arrays, filtering and mapping without writing manual loops.

Beginner 14 min read Lesson 4 of 300 Challenge included
What you will be able to do
  • Use [] for arrays and associative keys for records.
  • array_filter keeps values whose callback returns true.
  • array_map transforms every value.
  • Know that array_filter preserves keys unless you reindex.

In plain English

PHP arrays are ordered maps that can act as lists, dictionaries or both. array_filter and array_map express intent better than a manual loop, and array_column is perfect for pulling one field out of rows.

arrays.phpPHP
<?php
$courses = [
    ['title' => 'HTML', 'minutes' => 12],
    ['title' => 'CSS', 'minutes' => 18],
    ['title' => 'PHP', 'minutes' => 25],
];

$long = array_values(array_filter($courses, fn ($c) => $c['minutes'] >= 18));
$titles = array_column($long, 'title');

print_r($titles);
echo count($courses);
Your turn

Keep only long lessons

Easy

Given an array of minute counts, return a reindexed array containing only values of 15 or more.

PHP · starter
$minutes = [8, 15, 22, 4];
Check your understanding before moving on.
Knowledge checkQuestion 1

What does array_filter return when the callback returns true?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Forms and superglobals
Lesson 4 of 300 · 0% of course