In this PHP tutorial, you shall learn how to split a given string by comma separator using explode() function, with example programs.

PHP – Split String by Comma

To split a string by comma delimiter in PHP, use explode() function. Call explode() and pass the comma separator string, and given string as arguments.

Syntax

The syntax to split the string str by comma using explode() function is

</>
Copy
explode(',', $str)

The function returns an array of values.

Examples

1. Convert CSV string to Array of values

In this example, we will take a string 'apple,banana,cherry,mango' which is comma separated value. We split this string into an array of values.

PHP Program

</>
Copy
<?php
  $str = 'apple,banana,cherry,mango';
  $values = explode(',', $str);
  foreach ($values as $x) {
      echo $x;
      echo '<br>';
  }
?>

Output

PHP - Split String by Comma example

Conclusion

In this PHP Tutorial, we learned how to split a string by comma delimiter, using explode() function.