Understanding the preg_split function in PHP

Home > Search
  by

The preg_split function will create an array of items. For example, let's say you have a variable named myFruit that contains fruit.

$myFruit="apple banana orange pear";

 

When you echo $myFruit, the following will be displayed.

apple banana orange pear

 

myFruit can be split into an array.

$myFruit="apple banana orange pear";	
$item = preg_split('/[\s,]+/', $myFruit);
echo $item;

 

When you echo $item, 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:

  • $item[0] = apple
  • $item[1] = banana
  • $item[2] = orange
  • $item[3] = pear

Echoing each item can be used to print each item in the array.

echo $item[0];
echo $item[1];
echo $item[2];
echo $item[3];
apple banana orange pear

 


Foreach loop

A foreach loop can be used to loop through the items in the array.

$myFruit="apple banana orange pear";	
$item = preg_split('/[\s,]+/', $myFruit);

foreach ($item as $myItems) {
    echo $myItems;
}

 

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 in the box below so that we can be sure you are a human.




Comments