Now we're getting into one of the most important parts of PHP: arrays.
Think of them as "composite" variables, a bit like mini spreadsheets you can stuff full of values.
There's a lot you can do with arrays, and while they can be a bit tricky at first, you'll soon see they're absolutely essential. Once you get the hang of them, you'll have a solid grip on the fundamentals of PHP, and you'll be all set for what's coming next: practical, exciting stuff.
But enough chit-chat... hoist the sails, let's dive in!
Introduction to Arrays
An array is a variable. But not just any old variable.
Let's take a step back. Up until now, you've been using plain, simple variables: they have a name and a value.
For example:
<?php $firstName = 'Bob'; echo 'Hello ' . $firstName; // This will display: Hello Bob ?>
Which you could visualize like this:
Name | Value |
---|---|
$firstName | Bob |
But now we're going to see how you can cram a whole bunch of values into a single variable — way more than just "Bob" — using arrays.
For example:
Name | Value |
---|---|
$firstName | Bob |
$firstName | Jim |
$firstName | Tom |
$firstName | Sonic the Hedgehog |
$firstName | [etc...] |
There are two main types of arrays:
- Indexed arrays
- Associative arrays
And we're going to explore both kinds, because you'll definitely be using them in PHP.
Indexed Arrays
These are the easiest to picture. Take this example array stored in a variable called $firstNames:
Index | Value |
---|---|
0 | James |
1 | Mitch |
2 | Nicole |
3 | Valter |
4 | Alec |
... | ... |
$firstNames is an array — a variable that holds multiple values (and you can add as many as you want).
Each value lives in its own "slot" or "box." And since this is an indexed array, each slot has a number — that number is called the index.
✦ Creating an Indexed Array
To make an indexed array in PHP, the usual way is to use the array() function. Here's how you'd build the $firstNames array:
<?php // The array() function creates an array $firstNames = array('James', 'Mitch', 'Nicole', 'Valter', 'Alec'); ?>
Order matters! "James" is in position 0, Mitch in 1, and so on.
You can also build your array one item at a time, manually:
<?php $firstNames[0] = 'James'; $firstNames[1] = 'Mitch'; $firstNames[2] = 'Nicole'; ?>
Or — if you're feeling lazy (no judgment) — you can let PHP pick the index for you by leaving the brackets empty:
<?php $firstNames[] = 'James'; // PHP assigns index 0 $firstNames[] = 'Mitch'; // Now index 1 $firstNames[] = 'Nicole'; // And index 2 ?>
✦ Displaying an Indexed Array
To display an item, you just give PHP the index in square brackets after the variable name.
You're basically saying: "Hey PHP, give me what's in slot number 1 of $firstNames."
So, to display "Mitch," you'd write:
<?php echo $firstNames[1]; ?>
Easy, as long as you remember that Mitch is in the second spot, so his index is 1 (because counting starts at 0, remember? 😉).
If you forget the square brackets, PHP will just shrug and show you "Array" — which isn't very helpful. Whenever you're working with arrays, always use those brackets to tell PHP exactly which value you want!
Associative Arrays
Associative arrays work on the same general principle, but instead of numbering each slot, you label them with a unique name.
Let's say you want to store someone's contact details — name, first name, address, city, etc. If you use an indexed array, how would you know which number corresponds to what? Is 0 the name? Is 1 the address? Who knows?
This is where associative arrays shine.
✦ Creating an Associative Array
You still use the array() function, but this time, you label each value with a descriptive key:
<?php // Creating the $contactInfo array $contactInfo = array( 'firstName' => 'James', 'lastName' => 'Siteraw', 'address' => '313 Siteraw Avenue', 'city' => 'Phoenix' ); ?>
Notice the little arrow =>
— it means "associated with." So, 'city' => 'Phoenix'
reads as "city associated with Phoenix."
We've now built an array that looks like this:
Key | Value |
---|---|
firstName | James |
lastName | Siteraw |
address | 313 Siteraw Avenue |
city | Phoenix |
You can also create associative arrays one item at a time like so:
<?php $contactInfo['firstName'] = 'James'; $contactInfo['lastName'] = 'Siteraw'; $contactInfo['address'] = '313 Siteraw Avenue'; $contactInfo['city'] = 'Phoenix'; ?>
✦ Displaying an Associative Array
To display a value, just use its key in square brackets — and since keys are text, put them in quotes or apostrophes:
<?php echo $contactInfo['city']; ?>
As you've probably guessed from the examples:
- Indexed arrays are great for storing a list of similar items, like a bunch of first names. Each element is one item in that list.
- Associative arrays are best when you want to break down a single item into multiple labeled parts. For example, an address might include a first name, last name, street name, city, etc.
Looping Through an Array
Once you've created an array, chances are you'll want to take a peek inside to see what it's holding. There are three main ways to explore the contents of an array:
- The for loop
- The foreach loop
- The print_r function (mostly used for debugging)
The for Loop
The simplest way to loop through a numbered array is with a good ol' for loop. Since numbered arrays start at 0, you can just write a loop that counts up from zero. Like this:
// We create our $firstnames array $firstnames = array('James', 'Mitch', 'Nicole', 'Valter', 'Alec');// Then loop through it to display each name: for ($number = 0; $number < 5; $number++) { echo $firstnames[$number] . '<br />'; // displays $firstnames[0], $firstnames[1], etc. }
When you write $firstnames[$number], PHP first replaces $number with its value. So if $number is 2, then it fetches $firstnames[2], which is... Nicole! Congrats, you're getting the hang of it. :)
The foreach Loop
Sure, for loops work just fine. But PHP gives us a loop that's custom-built for arrays: foreach. Think of it as the deluxe, tailor-made array loop.
What foreach does is go through every item in the array, one by one, and temporarily puts the value of the current item into a variable (like $element).
Sounds a bit abstract? Don't worry — check this out:
$firstnames = array('James', 'Mitch', 'Nicole', 'Valter', 'Alec');
foreach($firstnames as $element) { echo $element . '<br />'; // displays each name in turn }
It's the same result as the for loop earlier, but written in a much more "array-friendly" way. At each loop, $element holds the next item in the array. Just use $element inside the loop to display the current name.
One big advantage of foreach is that it also works perfectly with associative arrays!
$coord = array( 'firstname' => 'James', 'name' => 'Siteraw', 'address' => '313 Siteraw Avenue', 'city' => 'Phoenix');foreach($coord as $element) { echo $element . '<br />'; }
Here, foreach cycles through the associative array $coord, and $element successively contains "James", "Siteraw", and so on.
You write inside the parentheses:
- The name of the array ($coord)
- The keyword as (as in "as this temporary variable")
- And finally, the name of the variable that'll hold each value, one at a time ($element in this case)
But wait! There's more. So far we've only been grabbing the value of each element. But what if we also want the key? Easy. Just write the foreach like this:
foreach($coord as $key => $element)
Now, in each loop iteration you get two variables:
- $key — holds the key of the current item ("firstname", "name", etc.)
- $element — holds the value ("James", "Siteraw", etc.)
Let's see this in action:
$coord = array( 'firstname' => 'James', 'name' => 'Siteraw', 'address' => '313 Siteraw Avenue', 'city' => 'Phoenix');foreach($coord as $key => $element) { echo '[' . $key . '] is ' . $element . '<br />'; }
Output:
[firstname] is James [name] is Siteraw [address] is 313 Siteraw Avenue [city] is Phoenix
Now you've got both the key and the value at your fingertips inside the loop. foreach is a real gem — you'll be using it a lot in your future PHP adventures!
Quick Array Display with print_r
Sometimes, when you're coding your PHP site, you'll have an array in hand and just want to see what's inside it. You could use a for loop or — better — a foreach. But if you don't care about formatting and just want a quick dump of the array's contents, call in the print_r function. It's like echo, but made for arrays.
One small catch: print_r doesn't add HTML line breaks (<br />
). So to get nice, readable output in the browser, we wrap it in a <pre>
tag, like this:
$coord = array( 'firstname' => 'James', 'name' => 'Siteraw', 'address' => '313 Siteraw Avenue', 'city' => 'Phoenix');echo '<pre>'; print_r($coord); echo '</pre>';
Super simple, as long as you don't forget the <pre>
tag to make the output look neat.
Of course, don't go showing this kind of output to your site visitors. print_r is meant for debugging only, to help you see what's inside an array during development.
Searching in an Array
Next up: searching through arrays! You'll often want to check if an array contains a certain piece of data. PHP gives us three built-in functions for that:
- array_key_exists — check if a key exists in an array
- in_array — check if a value exists in an array
- array_search — find the key corresponding to a value in an array
Checking if a Key Exists: array_key_exists
Let's say you've got an array, but you're not sure if it contains a particular key. Use array_key_exists to check.
It takes two arguments: the key you're looking for, and the array to search in:
array_key_exists('key', $array);
It returns true (yep, it's there) or false (nope, not found). Perfect for a quick if test:
$coord = array( 'firstname' => 'James', 'name' => 'Siteraw', 'address' => '313 Siteraw Avenue', 'city' => 'Phoenix');if (array_key_exists('name', $coord)) { echo 'The "nom" key is in the array!'; }
if (array_key_exists('country', $coord)) { echo 'The "country" key is in the array!'; }
As expected, we get the message for "name", but nothing for "country" — because "country" simply isn't there. Logic wins again. :)
Checking if a Value Exists: in_array
This one's very similar to array_key_exists, but now we're searching the values instead of the keys. in_array returns true if the value is found, and false if it's not.
Let's switch things up with a new array — of fruits this time! 🍌🍎🍓
$fruits = array('Banana', 'Apple', 'Pear', 'Cherry', 'Strawberry', 'Raspberry');if (in_array('Blueberry', $fruits)) { echo '"Blueberry" is in the fruits!'; }
if (in_array('Cherry', $fruits)) { echo '"Cherry" is in the fruits!'; }
Only the message for "Cherry" shows up. Why? Because in_array found it, but didn't find "Blueberry" (sad pepe).
Finding the Key of a Value: array_search
array_search is like the big brother of in_array. It also searches through the values, but if it finds the value, it gives you the corresponding key:
- If it does find the value, it returns the key (number or name depending on the array type)
- If it doesn't, it returns false
Let's go back to our fruity array (making me hungry 😋):
$fruits = array('Banana', 'Apple', 'Pear', 'Cherry', 'Strawberry', 'Raspberry');$position = array_search('Strawberry', $fruits); echo '"Strawberry" is at position ' . $position . '<br />';
$position = array_search('Banana', $fruits); echo '"Banana" is at position ' . $position;
And there you go! That wraps up our chapter on arrays! Just one more chapter left (on include — super important!) and you'll have completed Part 2 of this course. After that, we dive into the deep end with more advanced PHP concepts... and databases!
You might not realize it yet, but you've learned a ton. Honestly, this is the toughest part. At the beginning, everything seems confusing and pointless. But you've made it through — and that's huge. 🎉
From here on, the chapters will feel way more relaxed and fun to read. Keep up the great work — you're well on your way to becoming a PHP pro!
Enjoyed this PHP & MySQL course?
If you liked this lesson, you can find the book "How to Build a Website in HTML and CSS" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete PHP & MySQL workshop with many exclusive bonus chapters.