Precautions When Using Arrays - Images: Japanese
Hey there, everyone!
In the previous article, we covered the basics of defining arrays. Now let's look at some trickier ways to assign values to arrays, along with a few things to watch out for.
First, let's look at how to add a new value to the end of an array. Take a look at the sample below.
<?php
$arr = array('miku', 'IA');
Here we have an array called arr containing the strings 'miku' and 'IA'. To add a new value to it, you write it like this:
<?php
$arr = array('miku', 'IA');
$arr[] = 'rin';
Notice the [] tacked onto the end of arr, with the string 'rin' being assigned to it. This adds 'rin' to the array. Let's verify that with var_dump().
<?php
$arr = array('miku', 'IA');
$arr[] = 'rin';
var_dump($arr);
Running this gives you the following output:
array(3) {
[0]=>
string(4) "miku"
[1]=>
string(2) "IA"
[2]=>
string(3) "rin"
}
It was added perfectly. So in PHP, when you want to append a value to an array, just assign it using []. One thing to keep in mind: if you put a number inside the brackets, like $arr[2], that becomes an assignment to that specific index — not an append. Don't mix them up.
There's another way to append values to an array in PHP: array_push(). The syntax looks like this:
array_push(array_name, value_to_add);
<?php
$arr = array('miku', 'IA');
array_push($arr, 'rin', 'ren'); // Adds 'rin' and 'ren' to the array 'arr'.
This works fine for adding values to an array, but array_push() is generally used when you want to add multiple values at once. For adding a single value, [] is more concise and is the more common choice.
Now let's go over a few things to be aware of when defining arrays in PHP. Normally, array elements are stored using sequential index numbers, and some programming languages require you to use consecutive numbers. In PHP, however, you can skip index numbers and create elements at arbitrary positions.
Let's try it out. We'll create an empty array and immediately assign a value to index 3. We'll also practice using the [] syntax to define the array.
<?php $arr = []; // Create array 'arr'. $arr[3] = 'miku'; // Assign directly to index 3. var_dump($arr);
Running this gives you:
array(1) {
[3]=>
string(4) "miku"
}
No problem at all — it works just fine. So keep in mind that PHP arrays are not guaranteed to have sequential index numbers. This can catch you off guard if you're used to working in other languages.
Also, if you use [] to append to an array that has gaps in its index numbers, the new element is added at the next number after the current highest index. Let's try that out. Check out the sample below:
<?php $arr = []; // Create array 'arr'. $arr[3] = 'miku'; // Assign directly to index 3. $arr[] = 'IA'; // Append using []. var_dump($arr);
Here's the result:
array(2) {
[3]=>
string(4) "miku"
[4]=>
string(2) "IA"
}
Since the highest index in the array was 3, the string 'IA' was added at index 4. Worth keeping in mind.
Also, we mentioned in the previous article that associative arrays and regular arrays are treated the same way. An associative array is essentially an array where the index is a string instead of a number — but since they're treated the same, you can define an associative array using the same array() syntax. And here's a quirky thing: if you use a string that looks like a number as an index, PHP will treat it as an actual integer.
Let's see that in action. Check out the code below:
<?php $arr = ['miku']; // Create array 'arr' and assign 'miku' to index 0. $arr['0'] = 'IA'; // Assign 'IA' to the string-keyed index '0'. echo $arr[0]; // Output index 0 of array 'arr'.
So which value gets output — 'miku' or 'IA'? The answer is:
IA
It outputs 'IA'. The original value was completely overwritten. In PHP, a string that looks like a number and an actual integer are treated as the same thing, so watch out for that.
In PHP, if you declare a variable without assigning any value to it, it's treated as if it holds null. You pronounce it "null" (in Japanese contexts it's often said as "nuru", but the English pronunciation is closer to "nul"). null essentially means "nothing" or "no value". It's one of PHP's fundamental built-in values, just like true and false. We'll go into more detail in a later article.
<?php $test; // Declare variable 'test'. var_dump($test); // Outputs 'NULL'
null is case-insensitive, so NULL and even NuLl all work the same way. That said, stick to NULL or null to keep things readable.
Since null is a valid value in PHP, you can also assign it directly to a variable like this:
<?php $test = null; // Assign null to variable 'test'. var_dump($test); // Outputs 'NULL'.
One thing to note: as mentioned above, outputting an undefined variable or a non-existent array element returns NULL, but it also triggers a Notice. Here's what the output looks like when PHP error display is set to On:
<?php var_dump($test); // Try to output an undefined variable.
Notice: Undefined variable: test in /Users/username/Desktop/test/index.php on line 2 NULL
This is just PHP's way of saying "hey, something looks a bit off here." You can set error display to Off and ignore it if you want.
That said, since PHP is explicitly warning you about it, it's not great practice to just leave it and move on.
When you want to check whether a variable or array element exists, use isset(). Just pass the variable or array element you want to check inside the parentheses. It returns true if the value is defined and is not null, and false otherwise. Here's an example:
<?php $test; $test1 = 'miku'; $arr = []; var_dump(isset($test)); // 'test' is declared but has no value assigned, so it's null. Returns false. var_dump(isset($test1)); // 'test1' is declared and holds 'miku'. Returns true. var_dump(isset($arr[0])); // Index 0 of 'arr' doesn't exist. Returns false. var_dump(isset($arr1)); // Variable 'arr1' doesn't exist. Returns false.
isset() comes up all the time in PHP, so make sure you remember it.
And that covers the different ways to work with arrays in PHP, along with some important things to keep in mind. Feeling good about it?
We haven't seen many practical examples of arrays yet, so in the next article we'll look at some concrete use cases. Stay tuned!
See you in the next one!
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.