By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

PHP Explode Tutorial

This tutorial shows how to use php explode, and work with the resulting array.

Edited: 2013-04-18 14:01

Sometimes you want to split a long list into an array – the list being a single sting – this can be done by using php explode. When you use the explode function of php, it will return an array each containing a piece of the original string, starting with an id of 0.

The delimiter used to split the string, can be a single character, or a combination of characters. Its common to either have a comma, or space separated list of items. To split this into an array, the below php script can be used:

$keywords = 'HTML CSS HTML5 XHTML JavaScript PHP MySQL';
$pieces = explode(' ', $keywords);
echo $pieces[0]; // HTML
echo $pieces[1]; // CSS

How to handle exploded strings

The easiest way to work with the resulting array after using php explode, is to feed it to a while or for loop in php, but you will need to count the resulting array first, this is done with the php count function.

$n = count($pieces); // Number of Pieces

$counter = 0;
while ($counter <= $n) {
  echo $pieces["$counter"] . "\n";

  ++$counter;
}

This is just one way to work with the resulting array, you may also want to read the php tutorial on loops.

Using the limit parameter with php explode

The limit parameter can be useful when working with very large strings, or when you only want to slice a limited number of pieces.

To change things a bit, lets use a comma and a space as separator in the next example. The below is an example of how you can use the limit parameter with the explode function of php:

$keywords = 'HTML, CSS, HTML5, XHTML, JavaScript, PHP, MySQL';
$pieces = explode(', ', $keywords, 5);
$n = count($pieces); // Number of Pieces

$counter = 0;
while ($counter < $n) {
  echo $pieces["$counter"] . '<br>';
  ++$counter;
}

That would first output the first 5 pieces, and then the remaining string.

HTML
CSS
HTML5
XHTML
JavaScript
PHP, MySQL

To avoid that the remaining string is outputted, simply subtract 1 from the $n variable, before the loop. For example:

$n = count($pieces)-1;

You can also use a negative number as the limit, doing so will simply remove the number of pieces from the end that you specify. The following php script:

$keywords = 'HTML, CSS, HTML5, XHTML, JavaScript, PHP, MySQL';
$pieces = explode(', ', $keywords, -2);
$n = count($pieces); // Number of Pieces

$counter = 0;
while ($counter <= $n) {
  echo $pieces["$counter"] . '<br>';
  ++$counter;
}

Would result in:

HTML
CSS
HTML5
XHTML
JavaScript