root@coding-prodigies:~# โ–Š
// lesson 3 of 12 ยท 16 min

Arrays

โš‘ Report an issue with this lesson
$courses = ["HTML", "CSS", "Python"]; // indexed array

$prices = [
    "html" => 29.99,
    "sql" => 59.99,
]; // associative array

foreach ($prices as $key => $value) {
    echo "$key: $value\n";
}

PHP arrays double as both lists and dictionaries -- the same type handles what Python splits into separate list and dict types. Under the hood, even an "indexed" array like ["HTML", "CSS", "Python"] is really an ordered map with implicit integer keys 0, 1, 2, which is why you can mix the two styles or have gaps in the numbering if you're not careful.

PHP ships a large standard library of array functions that cover most of what you'd otherwise write a loop for. Some of the most common:

$prices = [29.99, 149.99, 59.99];

$total = array_sum($prices);                     // 239.97
$affordable = array_filter($prices, fn($p) => $p < 100); // [0 => 29.99, 2 => 59.99]
$discounted = array_map(fn($p) => $p * 0.9, $prices);      // apply to every element
$names = ["html", "css", "python"];
$pairs = array_combine($names, $prices);           // zip two arrays into one

sort($prices);        // re-indexes and sorts ascending in place
in_array(59.99, $prices);  // true
count($prices);            // 3

Note that array_filter preserves the original keys rather than re-indexing -- if you need a clean, re-indexed array afterward, wrap the result in array_values(). This trips up a lot of PHP beginners who then try to loop over the "filtered" array with numeric indices starting from 0 and get unexpected gaps.

Arrays can also nest arbitrarily, which is how PHP represents JSON-like structures before you even bring in a database:

$course = [
    "title" => "PHP Mastery",
    "price" => 149.99,
    "tags" => ["backend", "web"],
];

echo $course["tags"][0]; // "backend"
echo json_encode($course); // turns the nested array into a JSON string

Try it yourself

Exercise: Build an associative array of 2 courses and prices, then loop and echo each.
Expected output: open-ended โ€” there's no single correct output here, just get your code running without errors.
php
Output

      
    

Run your code and get it working before marking this lesson complete.

// that was the last free lesson

9 more lessons โ€” including Capstone project: a course listing page โ€” plus a certificate are waiting.

Unlock the full course โ€” $149.99