Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 7 / 68

Working with Arrays

In this lesson you will learn the basics of arrays in PHP so you can handle several pieces of data together. This is for anyone searching for "PHP array how to use" or "PHP foreach".

An array is like a shelf of numbered drawers. You create one with [ ] and take the items out one at a time with foreach. It is the most fundamental data structure, indispensable whenever you want to manage several values of the same kind.

The sample code builds a $fruits array and uses foreach ($fruits as $i => $fruit) to pull out the index ($i) and the value ($fruit) at the same time. Being able to take the key and the value together makes foreach very handy for arrays.

A common stumbling block for beginners is that array indexes start at 0. $fruits[1] refers to the second element, and that off-by-one feeling is a fertile source of bugs. Adjusting the display with $i + 1 to get numbering that starts at 1 is a common move.

Associative arrays, where the keys are strings rather than numbers, are one of PHP's real strengths. They come up constantly for data you want to label, such as user details or configuration values.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)