How to split string by comma in PHP?

Member

by mac , in category: PHP General , 2 years ago

How to split string by comma in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by darrion.kuhn , 2 years ago

@mac 

In PHP, you can use the explode() function to split a string by a specified delimiter, such as a comma. Here's an example of how to use explode() to split a string by a comma:

1
2
3
4
5
6
7
8
9
$string = "hello,world,how,are,you";
$pieces = explode(",", $string);

// $pieces is now an array containing each part of the string
// $pieces[0] = "hello"
// $pieces[1] = "world"
// $pieces[2] = "how"
// $pieces[3] = "are"
// $pieces[4] = "you"

Alternatively, you can use the str_split() function to split a string into an array of individual characters. Here's an example of how to use str_split() to split a string by a comma:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$string = "hello,world,how,are,you";
$pieces = str_split($string, 1);

// $pieces is now an array containing each character of the string
// $pieces[0] = "h"
// $pieces[1] = "e"
// $pieces[2] = "l"
// $pieces[3] = "l"
// $pieces[4] = "o"
// ... and so on

Note that str_split() will split the string into individual characters, rather than by a specific delimiter like explode() does. So if you want to split a string by a specific delimiter, such as a comma, you should use explode() instead.

by lindsey.homenick , a year ago

@mac 

To split a string by comma in PHP, you can use the explode() function. The explode() function splits a string into an array of substrings based on a specified delimiter.


Here's an example:

1
2
$string = "apple,banana,cherry";
$array = explode(",", $string);


In this example, the explode() function splits the $string variable into an array called $array using the comma (",") as the delimiter. After splitting, the $array will contain three elements: "apple", "banana", and "cherry".


You can then access the individual elements of the array using their respective indexes:

1
2
3
echo $array[0]; // Output: apple
echo $array[1]; // Output: banana
echo $array[2]; // Output: cherry


Alternatively, you can use the str_getcsv() function to split a CSV string into an array. CSV stands for Comma-Separated Values. Here's an example:

1
2
$string = "apple,banana,cherry";
$array = str_getcsv($string);


The str_getcsv() function automatically splits the string based on commas and handles cases where the values may contain commas as well.