OneBite.Dev - Coding blog in a bite size

Split A String By Comma Sign In PHP

Code snippet for how to Split A String By Comma Sign In PHP with sample and detail explanation

Whether you’ve just started learning PHP or have been using it for years, splitting strings by a comma can be a common requirement for a number of applications. This article will guide you through the process of splitting a string by a comma sign in PHP, explaining all the necessary steps in an accessible manner.

Code snippet for Splitting a String by a Comma in PHP

Below is a simple, concise snippet of PHP code that will split a string by a comma.

<?php
$string = "apple,banana,cherry";
$array = explode(',', $string);
print_r($array);
?>

Code Explanation for Splitting a String by a Comma in PHP

Let’s break down what we’re doing in this snippet.

The first line of the code is a standard opening PHP tag. This tells the server that the following content will be PHP code.

<?php

The next line defines a string variable $string with three fruits “apple”, “banana”, and “cherry” separated by commas.

$string = "apple,banana,cherry";

After that, we use the explode() function to split the string. The explode() function in PHP splits a string by a string. It takes two parameters. The first parameter defines the symbol or sequence of symbols to split by (in our case, a comma) and the second parameter refers to the string we want to split.

$array = explode(',', $string);

The final line prints out the created array, which should look like this: Array ( [0] => apple [1] => banana [2] => cherry )

print_r($array);
?>

The closing tag signals the end of the PHP code.

That’s it! You have now successfully split a string by a comma in PHP. This simple tool can be very practical in many situations where you need to manipulate or analyze data in PHP.

php