Chapter practice task
Task: Build a services list page from an array
- Create an array of at least four services, each with a name, price and short description.
- Loop over it with foreach and print each service as an HTML card.
- Write a
format_price()function that returns a price like “$1,200”. - 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.