How to split string by comma in PHP?

Member

by mac , in category: PHP General , 9 months ago

How to split string by comma in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 3 months 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.