0
0
PHPprogramming~5 mins

String split and explode in PHP

Choose your learning style9 modes available
Introduction
Splitting a string helps you break a sentence or list into smaller parts so you can use each piece separately.
You have a list of names separated by commas and want to get each name alone.
You receive a sentence and want to count or use each word separately.
You get data from a file or user input where items are joined by a special character.
You want to separate a date like '2024-06-01' into year, month, and day.
Syntax
PHP
explode(string $delimiter, string $string, int $limit = PHP_INT_MAX): array
The delimiter is the character or string where you want to cut the original string.
The limit is optional and controls how many pieces you get back.
Examples
Splits the string by commas into an array of fruits.
PHP
$parts = explode(",", "apple,banana,orange");
print_r($parts);
Splits the sentence into words using space as the separator.
PHP
$words = explode(" ", "Hello world from PHP");
print_r($words);
Splits into maximum 3 parts; the last part contains the rest.
PHP
$limited = explode(",", "one,two,three,four", 3);
print_r($limited);
Sample Program
This program splits a string of colors separated by commas and prints each color on its own line.
PHP
<?php
// Example: split a list of colors
$colors = "red,green,blue,yellow";
$colorArray = explode(",", $colors);

foreach ($colorArray as $color) {
    echo "Color: $color\n";
}
?>
OutputSuccess
Important Notes
If the delimiter is not found, explode returns an array with the original string as the only element.
Using an empty string as delimiter will cause a warning; always use a valid delimiter.
The explode function is case-sensitive when matching the delimiter.
Summary
Use explode() to break a string into parts based on a delimiter.
It returns an array of strings you can use separately.
You can limit how many pieces you want with the optional third parameter.