FreeKB - PHP preg_split (split a string)
PHP - preg_split (split a string)

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. 



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


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 2e36b in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |