- PHP

How to use explode() function in PHP

The explode() function allows us to split a string by a string.

explode($separator, $string, $limit);

With PHP’s explode() function, we can easily create an array from a string by separating the individual values with a specific separator. If our string contains values separated by, for example, newlines, commas, dots, slashes, dashes, other symbols, or even entire text sequences, the explode() function will allow us to separate them and create an easy-to-use array.

Example 1:

Make an array from comma-separated string.

<?php

$fruits = 'apples, oranges, watermelons';

$fruitsArray = explode(', ', $fruits);

print_r($fruitsArray);

Output:

Array ( [0] => apples [1] => oranges [2] => watermelons )

Example 2:

Make an HTML list from string separated with new lines.

<?php

$names = 
'Alex
Anna
Pamela
Jessica
Max';

$namesArray = explode(PHP_EOL, $names);

echo '<b>Names:</b>';
echo '<ul>';
    foreach($namesArray as $name) {
        echo '<li>'.$name.'</li>';
    }
echo '</ul>';

Output:

Names:
  • Alex
  • Anna
  • Pamela
  • Jessica
  • Max