What are Arrays? - Images: Japanese
Hey everyone, hope you're doing well!
Today we're tackling 'arrays' — another topic that tends to trip up beginners, just like variables did. It might feel a little tricky at first, but let's work through it together.
So, "what even is an array?" An array is a 'collection of variables identified by sequential numbers'. The key ideas are that variables are grouped together, and each one is assigned a number. No, you can't eat it.
Here's a practical example: say you want to store employee names and then output a count of them. If you could bundle all the name variables together, you'd end up with much cleaner code. That's exactly what arrays are for.
We'll cover how to actually use an array in the next article — for now, let's focus on how to define one.
In most programming languages, arrays come in two flavors: indexed arrays (also called numeric arrays), where items are identified by sequential numbers, and associative arrays (also called hashes), where items are identified by specific string keys.
PHP supports both indexed arrays and associative arrays — but internally, PHP treats them as the same thing.
In many other languages, indexed and associative arrays are strictly separate, with different syntax and usage rules. PHP takes a more relaxed approach, which can be a bit confusing if you're coming from another language — so keep that in mind.
One side effect of this: you can actually define an associative array using the same syntax as a regular indexed array. It's one of PHP's quirks.
Also worth noting: when people say "array" without any qualifier, they're usually referring to an indexed array.
The classic way to define an array in PHP — available since the early days — is to use 'array()'. That's pronounced "ah-ray", by the way. Here's what it looks like:
<?php $arr = array();
array() is assigned to $arr, which means $arr is now defined as an array. It can hold multiple values, each identified by a sequential number.
By the way, the name you give to an array is called the array name. Pretty straightforward, but worth knowing the term.
Now let's assign the string miku to index position 0 of the array. Here's how:
<?php $arr = array(); $arr[0] = 'miku';
As shown above, you write the array name followed by '[]' (square brackets, also called brackets), put the index number inside, and assign a value to it. That's all there is to it.
One important note here: "why does it start at 0?" Well, in programming, sequential numbering starts from 0, not 1. This is consistent across virtually all programming languages, so make sure to remember it.
The number inside the brackets — like 0 or 1 — is called an index (or index number). Worth memorizing that term too.
You can also pre-populate an array with values by listing them inside ',' (comma)-separated inside the parentheses of 'array()'. Like this:
<?php
$arr = array('miku', 'IA');
In the example above, the array $arr is defined with two elements: the string miku and the string IA.
To store numbers instead, it looks like this:
<?php $arr = array(100, 200);
Since PHP 5.4, you can use [] instead of array() to define an array. Here's how that looks:
<?php $arr = []; // Same as writing '$arr = array();'
To initialize with values, just put them inside [] separated by ,.
<?php
$arr = ['miku', 'IA']; // Same as writing '$arr = array('miku', 'IA');'
It's quick and convenient — most developers these days use the '[]' syntax, so it's well worth getting comfortable with.
Now let's look at how to output and inspect the array — but first, one more thing to be aware of.
In previous articles, we used 'echo' to output variable values. The thing is, 'echo' does not expand and print the contents of an array. Same goes for 'print'. Let's see what happens if we try it with the array we just defined:
<?php
$arr = array('miku', 'IA');
echo $arr;
Running this gives you the following (when PHP error reporting is set to Off):
Array
All you get is "Array". As you can see, 'echo' doesn't show you what's actually inside the array.
Trying to develop without being able to inspect your arrays is pretty rough. "I just want to see what's in there..." — and that's exactly where var_dump(), introduced in a previous article, comes to the rescue. Let's rewrite the above using var_dump():
<?php
$arr = array('miku', 'IA');
var_dump($arr);
Here's what you get when you run it:
array(2) {
[0]=>
string(4) "miku"
[1]=>
string(2) "IA"
}
Super detailed output! You can see exactly what's inside the array and keep moving forward with development.
'var_dump()' tells you more than you even asked for — every detail about the contents. Since it also outputs type information, it's a developer's best friend when you need to inspect something.
Let's break down what the output means. The first line, 'array(2)', means "this is an array with 2 elements". Each individual piece of data inside an array is called an 'element'.
Next, look at '[0]=> string(4) "miku"'. This tells you: "element at index 0 is a string of 4 characters: 'miku'". The same pattern applies to '[1]=> string(2) "IA"'.
Now that we know how to define an array and inspect it, let's look at how to pull individual elements out of it.
To retrieve the value of a specific element, use []. To get the element at index 0 from the array we defined earlier:
<?php
$arr = array('miku', 'IA');
echo $arr[0];
Pretty similar to how we assigned the value earlier, right? Just put the index number you want inside [] and you're good to go. Running this outputs:
miku
Works perfectly.
Just to clarify the difference: if you want to output individual elements of an array one by one, echo (or print) is fine. If you want to dump the entire array to check its contents, use var_dump(). It's easy to mix these up, so keep the distinction in mind.
This article is getting long, so let's wrap it up here. In the next one, we'll look at some trickier ways to assign values to arrays, along with a few gotchas to watch out for. See you then!
This article was written by Sakurama.
Author's beloved small mammal |
桜舞 春人 Sakurama HarutoA 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 contact us.