Convert a String into an Array in PHP
One of the most common tasks in PHP is converting a string into an array. This can be especially useful when working with CSV files or other data that is delimited by commas.
Fortunately, PHP makes it easy to split a string into an array using the explode(), split(), or preg_split() functions.
- The explode() function takes two arguments: the string to be split and the delimiter.
- The split() function is similar to explode(), except that it uses a regular expression as the delimiter.
- The preg_split() function is the same as split(), except that it uses a regular expression as the delimiter. This can be useful when you need to split a string into an array based on a specific pattern.
$fruit = 'apple,orange,banana,pear';
$fruit_array = explode(',', $fruit);
print_r($fruit_array);
/* Result: Array (
0 => apple
1 => orange
2 => banana
3 => pear
) */
$color = 'red|green|blue';
$color_array = split('\|', $color); // Note: must escape | character with \
print_r($color_array);
$columns = "ID,Name,Age,Email,Username";
$columnsArray = preg_split("/\,/", $columns);