How to split a string into an array in PHP?

by herminia_bruen , in category: PHP General , 7 months ago

How to split a string into an array in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 7 months ago

@herminia_bruen 

In PHP, you can split a string into an array using the explode() function. This function splits a string into an array by a specified delimiter.


Here is an example of using explode() to split a string into an array:

1
2
3
4
5
6
$string = "Hello, world! How are you?";
$delimiter = " "; // split the string at every space

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

print_r($array);


Output:

1
2
3
4
5
6
7
8
Array
(
    [0] => Hello,
    [1] => world!
    [2] => How
    [3] => are
    [4] => you?
)


In this example, the explode() function is used to split the string $string into an array using the delimiter $delimiter, which is a space character. The resulting array $array contains each word from the original string as a separate element.


You can also use other delimiters, such as commas or semicolons, by changing the value of the $delimiter variable.