Open In App

How to Split a String into an Array in PHP ?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In PHP, splitting a string into an array involves breaking a string into smaller parts based on a delimiter or a pattern and storing those parts as elements of an array.

This operation is useful for parsing text data, extracting substrings, or processing user input. PHP provides several functions to split a string into an array, including explode( ), str_split( ), and preg_split( ).

Function Description
explode( ) Splits a string into an array of substrings based on a specified delimiter.
str_split( ) Splits a string into an array of characters, with each character becoming an element of the array.
preg_split( ) Splits a string into an array using a regular expression pattern as the delimiter.

Example: Implementation to split a string into an array.

PHP




<?php
// Using explode() function
   
$string = "apple,banana,orange";
$array1 = explode(",", $string);
echo "Using explode(): ";
print_r($array1);
 
// Using str_split() function
 
$string = "hello";
$array2 = str_split($string);
echo "Using str_split(): ";
print_r($array2);
 
// Using preg_split() function
 
$string = "apple, banana, orange";
$array3 = preg_split("/,\s*/", $string);
echo "Using preg_split(): ";
print_r($array3);
?>


Output:

Using explode(): Array
(
[0] => apple
[1] => banana
[2] => orange
)
Using str_split(): Array
(
[0] => h
[1] => e
[2] => l
[3] => l
[4] => o
)
Using preg_split(): Array
(
[0] => apple
[1] => banana
[2] => orange
)

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads