PHP for splitting a string by a delimiter


PHP Function for Splitting a String by a Delimiter

Code:

function splitStringByDelimiter($string, $delimiter) {
  // Convert the string to an array using the explode() function
  $array = explode($delimiter, $string);

  // Return the resulting array
  return $array;
}

Explanation:

This function takes two parameters: the string to be split and the delimiter to split by. It utilizes PHP’s built-in explode() function, which divides a string into an array based on a specified separator. The explode() function takes two arguments: the delimiter and the string to be split.

In this function, the $delimiter variable represents the separator you wish to split the string by. For example, if you want to split a string on commas, you would pass ‘,’ as the $delimiter argument.

Once the string is converted to an array, the function returns the array containing the split string elements.

Example Usage:

$string = "apple,banana,cherry,grape,orange";
$delimiter = ",";

$array = splitStringByDelimiter($string, $delimiter);

// Output the resulting array
echo "<pre>";
print_r($array);
echo "</pre>";

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
    [3] => grape
    [4] => orange
)