
If you are not familiar with arrays, check out our Getting Started article.
The preg_split function will split a string into an array. For example, let's say you have a variable that contains fruit.
$fruit="apple banana orange pear";
When you echo $fruit, the following will be displayed.
apple banana orange pear
$fruit can be split into an array. In this example, values are split where there is white space [\s]+.
$array = preg_split('/[\s]+/', $fruit);
When you echo $array, just the word "Array" will be displayed.
Array
This happens because each item in the array is now associated with a numeric identifier. In this example, the mapping between the items in the array is:
- $array[0] = apple
- $array[1] = banana
- $array[2] = orange
- $array[3] = pear
Echoing each item can be used to print each item in the array.
echo $array[0];
echo $array[1];
echo $array[2];
echo $array[3];
apple banana orange pear
Foreach loop
A foreach loop can be used to loop through the items in the array.
foreach ($array as $value) {
echo $value;
}
The output of the foreach loop will be:
apple banana orange pear
Did you find this article helpful?
If so, consider buying me a coffee over at