PHP Array Functions
With all the great features being added to PHP, it’s easy to forget that the PHP Standard Library contains a wealth of functions. This article will discuss some of the array-related functions, and their gotchas.
Exploding Strings
When you want to break a string into a parts, use the explode function. The explode()
function takes a string that delimits or divides the content. Some common delimiters are colons(:
), semicolons(;
), and dashes(–
). If you wanted to separate a string into individual characters, you’d be tempted to use an empty string as a delimiter. In doing so, you’ll get the following message, without getting the array of characters you want.
Warning: explode(): Empty delimiter
Instead, you’ll want to use the str_split() function for this use case.
$word = 'mankind';
$letters = str_split($word);
print_r($letters);
Array
(
[0] => m
[1] => a
[2] => n
[3] => k
[4] => i
[5] => n
[6] => d
)
Gaps in your data
As you use more array functions, you’ll see a note – array keys are preserved
– in the documentation on php.net for ta given function. The function reference for array_diff() is one of these pages.
To demonstrate this idea, let’s used the array_diff()
function to remove all the vowels from the world mankind.
$mankind = str_split('mankind');
$vowels = str_split('aeiou');
$result = array_diff($mankind, $vowels);
print_r($result);
The array_diff()
function will examine the first array $mankind
, and remove from it any of the values it finds in the second array $vowels
. Using print_r()
displays the structure of the array.
Array
(
[0] => m
[2] => n
[3] => k
[5] => n
[6] => d
)
Notice the indexes. Index 1 and index 4 have been removed! If you loop over this with foreach, everything will look normal. However, if your code is accessing specific indexes, you’ll experience a problem with non-existent data. It may even feel random
, because it works for most of your data in the array. So how do you get rid of these gaps?
Removing the gaps
To solve this, you’ll want to re-index your array. The array_values() function is the best option for this use case. This will keep all the data, while re-number the indexes. This removes any numerical gaps in the array.
$new_result = array_values($result);
print_r( $result);
Array
(
[0] => m
[1] => n
[2] => k
[3] => n
[4] => d
)
The array_merge()
function will also re-index an array. However, when you look back at the code later, you don’t want to wonder why you used the array_merge function on one array.
If you do have multiple arrays, array_merge()
makes more sense. For arrays with numeric indexes, the array_merge()
function will take each of them, effectively append one to the other and fix the indexes. This can be quite useful depending upon your program logic.
Wrap Up
In this article you learned how to split a string as individual characters into an array, about the cause of data gaps, and how to remove the gaps. Hopefully you’ve found this useful, and solves your problem.