Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. PHPBeginner - How to Use Arrays

How to Use Arrays - Images: Japanese

Hey there, everyone!

So far in this series, we've covered how to write arrays and the various things to watch out for. But we haven't really shown many practical examples of arrays actually being used. Without that, you might be left wondering: "Where exactly do I use arrays, and when?"

So let's write a small program — something just meaningful enough to give you a feel for how powerful arrays really are. Think of arrays as a way to bundle a bunch of variables together into one neat package.

The program we're building: a program that automatically outputs the number of Vocaloid characters.

It doesn't have to be Vocaloids, of course — but let's go with Vocaloids. Counting the number of old guys (the office staff) wouldn't exactly be riveting.

First, let's look at what happens if we use regular variables instead of an array. We'll define a few variables and assign each Vocaloid's name to one.

<?php
$vocaloid1 = 'Hatsune Miku';
$vocaloid2 = 'IA';
$vocaloid3 = 'Kagamine Rin';

There are 3 Vocaloids here. If we want to output that count using only what we've covered so far, we'd end up writing something like this.

<?php
$vocaloid1 = 'Hatsune Miku';
$vocaloid2 = 'IA';
$vocaloid3 = 'Kagamine Rin';

echo 'There are 3 Vocaloids.';

This does output "There are 3 Vocaloids." — but it doesn't feel very programming-like, does it? We never actually use the variables we defined, and worse, the programmer manually counted "3" themselves. The point of programming is to write the logic and let the computer do the calculating, so this approach falls a bit short.

PHP has no built-in way to count the number of individual variables. That's true for most other languages too. So with plain variables alone, building a "program that automatically outputs the Vocaloid count" just doesn't work well.

Now let's rebuild this using an array. We'll start by defining the array. The name can be anything — we'll go with vocaloids.

<?php
$vocaloids = [];

Now let's add each Vocaloid's name to the array using [].

<?php
$vocaloids = [];
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';

By the way, some languages require you to declare an array before using it, but PHP doesn't. That said, writing the declaration line does make it clear to other readers that "this is being defined here," so it can improve readability. Use your judgment depending on the situation.

<?php
// $vocaloids = []; // Array declaration line commented out.
$vocaloids[] = 'Hatsune Miku'; // You can start using it as an array right away like this.
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';

Now here's where things get interesting. Because we're using an array, all the data (the Vocaloid names) is neatly bundled together. So if we can output the count of items in this array, we'll effectively be outputting the number of members. That's where the count() function comes in. It returns the number of elements in an array. Let's try it out. The syntax is simple — put the array you want to count inside the parentheses of count().

<?php
$vocaloids = [];
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';

echo count($vocaloids); // Get the number of elements in the array 'vocaloids' with count(), then output it with echo.

Running this gives us the following output.

3

The array count is output correctly. From here, we just combine count() with string concatenation to put together the message we want.

<?php
$vocaloids = [];
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';

echo 'Number of Vocaloids: ' . count($vocaloids);

Now it actually feels like programming! This is a proper "program that automatically counts and outputs the number of Vocaloid members," so if new members are added, the output will update accordingly.

<?php
$vocaloids = [];
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';
$vocaloids[] = 'Kagamine Len'; // Adding 'Kagamine Len' to the array.

echo 'Number of Vocaloids: ' . count($vocaloids); // This correctly outputs 4.

Now let's take this a step further and add one more feature. Right now the program only tells us how many members there are — let's also make it output the name of the most recently added member.

The straightforward approach would be to just output the last element of the array directly, like this.

<?php
$vocaloids = [];
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';
$vocaloids[] = 'Kagamine Len';

echo 'Number of Vocaloids: ' . count($vocaloids);
echo 'The latest member is ' . $vocaloids[3] . '.';

This technically works, but it's a bit fragile. Every time the number of members changes, we'd have to manually update the index number — $vocaloids[3] in this case. That's not great from a programming standpoint. We want the program to automatically figure out who the last member is.

Here's a handy trick with arrays: you can put a variable inside the [] that holds the index. You can even put an expression in there and it'll evaluate it. Take this example using a variable.

<?php
$vocaloids = [];
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';
$vocaloids[] = 'Kagamine Len';
$cnt = 3; // Store the index of the last element in variable 'cnt'.

echo 'Number of Vocaloids: ' . count($vocaloids);
echo 'The latest member is ' . $vocaloids[$cnt] . '.'; // Access the array element using the value of 'cnt'.

So if we can put an expression inside [] that automatically retrieves the index of the last element, we can output the last member automatically.

If you've already figured it out — yes, we combine this with count().

There's one thing to be careful about though. The count() for the vocaloids array above returns 4. But the index of the last element is 3.

Recall that array indexes start at 0. That means to get the index of the last element, we need to subtract 1 from the value returned by count().

That -1 is the part that trips people up. For what it's worth, the value returned by count() is an actual number, so you can use it in arithmetic right away.

So the answer is to use count($vocaloids) - 1 as the index into the vocaloids array. It uses the array's own count as an index back into itself — which can feel a little mind-bending at first, but stick with it. Here's the finished version.

<?php
$vocaloids = [];
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';
$vocaloids[] = 'Kagamine Len';

echo 'Number of Vocaloids: ' . count($vocaloids);
echo 'The latest member is ' . $vocaloids[count($vocaloids) - 1] . '.';

Running this gives us the following output.

Number of Vocaloids: 4The latest member is Kagamine Len.

Looking good! Now let's test it by adding a new member, Megurine Luka.

<?php
$vocaloids = [];
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';
$vocaloids[] = 'Kagamine Len';
$vocaloids[] = 'Megurine Luka';

echo 'Number of Vocaloids: ' . count($vocaloids);
echo 'The latest member is ' . $vocaloids[count($vocaloids) - 1] . '.';

Running this gives us:

Number of Vocaloids: 5The latest member is Megurine Luka.

As elements are added to the array, both the count and the last element update automatically. This is working exactly as we wanted.

There's a function called sizeof() that also counts the number of elements in an array, just like count().

sizeof() does exactly the same thing as count(), so you can use whichever one you prefer. PHP has quite a few pairs of functions like this that do identical things.

And that's a wrap! We've covered just one example here, but this is a typical way arrays get used. Performing the right operation based on the number of elements in an array is a fundamental algorithm — and a very commonly used pattern.

An algorithm in programming refers to the procedure used to achieve a desired result. In short, it's the method of computation.

In programming, the ideal is to accomplish a task in the fewest steps possible. When you manage to build a complex process into a super compact piece of code, it's a satisfying feeling — "you can't help but admire yourself a little ... now that's a job well done."

Skilled programmers tend to be especially good at crafting clean algorithms.

Arrays come up constantly in topics like for loops, which we'll cover in later articles — so you'll get plenty more practice with them there. If you're not feeling totally confident yet, that's fine. Just keep moving forward!

In the next article, we'll be diving into functions. See you there!

This article was written by Sakurama.

Author's beloved small mammal

桜舞 春人 Sakurama Haruto

A Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him.

If you find any errors or copyright issues, please .