Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP program to split a given comma delimited string into an array of values
To split a given comma delimited string into an array of values, PHP provides several built-in functions like explode() and preg_split(). Both methods effectively convert a comma-separated string into an array.
Using explode() Function
The explode() function is the most straightforward method to split a string by a specific delimiter ?
<?php
$my_string = "456,789,23,4,019";
$my_str_arr = explode(",", $my_string);
print_r("The array is ");
print_r($my_str_arr);
?>
The array is Array
(
[0] => 456
[1] => 789
[2] => 23
[3] => 4
[4] => 019
)
Using preg_split() Function
The preg_split() function uses regular expressions for more complex splitting patterns ?
<?php
$my_string = "00, 876, 5432, 1234, 0";
$my_str_arr = preg_split("/,/", $my_string);
print_r("The array is ");
print_r($my_str_arr);
?>
The array is Array
(
[0] => 00
[1] => 876
[2] => 5432
[3] => 1234
[4] => 0
)
Handling Whitespace
To remove extra whitespace around values, combine splitting with array_map() and trim() ?
<?php
$my_string = "apple, banana, cherry, date";
$my_str_arr = array_map('trim', explode(",", $my_string));
print_r($my_str_arr);
?>
Array
(
[0] => apple
[1] => banana
[2] => cherry
[3] => date
)
Comparison
| Function | Use Case | Performance |
|---|---|---|
explode() |
Simple string splitting | Faster |
preg_split() |
Complex patterns with regex | Slower |
Conclusion
Use explode() for simple comma-separated strings and preg_split() for complex patterns. Always consider trimming whitespace for cleaner results.
Advertisements
