Skip to content
Chapter 02 of 05 · 3 lessons · ~28 min

Loops, Arrays and Functions

Repeat work with loops, store lists in arrays and package code into reusable functions.

YOUR PROGRESS0%
/ Lessons in this chapter
04
PHP Loops: for, while and foreach How to repeat code with for, while and foreach, and when to use each one. Coming soon
05
PHP Arrays Explained How to store lists of data in arrays, read and change them, and use the most helpful array functions. Coming soon
06
PHP Functions for Beginners How to write your own functions so you stop repeating code, and how parameters, return values and scope work. Coming soon

Chapter practice task

Task: Build a services list page from an array

  1. Create an array of at least four services, each with a name, price and short description.
  2. Loop over it with foreach and print each service as an HTML card.
  3. Write a format_price() function that returns a price like “$1,200”.
  4. Show a “Popular” badge on the service with the highest price.

By the end of this chapter

  • You can repeat code with for, while and foreach
  • You can create, read, change and sort arrays
  • You can write functions with parameters, default values and return values
  • You can turn data into HTML without copying markup by hand

Quick answers for this chapter

Which loop should I use most?

foreach. Most of the time you’re looping over an array, and foreach is made for that.

What’s an associative array?

An array with named keys, like ['name' => 'Logo design', 'price' => 300], instead of numbered positions.

Why use functions?

To write code once and reuse it everywhere. If you fix a bug in a function, it’s fixed everywhere it’s used.