Explode and implode
The explode functions splits a string by another string into an array of strings. implode joins an array of strings with a string.
Both of these functions can be very useful and in this tutorial we'll be looking at how to use both.
Explode
As mentioned above, explode splits a string into an array of strings by another string. This sounds a bit complex but it really isn't, an example is the best way to explain its usage:
<?php
$string = 'path/to/a/file.php';
$bits = explode('/', $string);
print_r($bits);
?>
This code will output:
Array
(
[0] => path
[1] => to
[2] => a
[3] => file.php
)
The explode function, in this example, takes 2 parameters - the first is the string to split by (called delimiter) and the second is the string to split. In the above example a file path stored in variable $string is split by '/'. The result is an array of 4 items. And that is the basics of the explode function!
The limit parameter
There is a third optional parameter of the explode function called limit. This allows you to limit the length of the final array. Using the same example as above but with a limit of 2 we get the following code and subsequent result:
<?php
$string = 'path/to/a/file.php';
$bits = explode('/', $string, 2);
print_r($bits);
?>
This code will output:
Array
(
[0] => path
[1] => to/a/file.php
)
The limit parameter results in the string being split only as many times as the size of limit will allow. The rest of the string is stored in the last element of the array.
Implode
The implode function is pretty much the opposite of the explode function. Where explode splits a string by a string into an array, implode joins an array with a string into a string. Again, an example best demonstrated its functionality:
<?php
$array = array(1, 2, 3, 4, 5);
$string = implode(', ', $array);
echo $string;
?>
This outputs a the elements of the array joined together with the 'glue' - in this case ', ':
1, 2, 3, 4, 5
And that is the implode function! The glue parameter is not required - if you do not supply it the array will simply be 'stuck' together with no glue:
<?php
$array = array('a', 'b', 'c', 'd', 'e');
$string = implode($array);
echo $string;
?>
Output:
abcde