How do you split a string into an array?

Use explode() to split a string into an array at a separator, like a comma. Here the extra spaces after the commas are removed with trim().

<?php
$languages = "PHP, HTML, CSS, JavaScript, MySQL";

$list = array_map("trim", explode(",", $languages));

print_r($list);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => PHP
[1] => HTML
[2] => CSS
[3] => JavaScript
[4] => MySQL
)

To split a string into single characters use str_split(). To split by a pattern (like many spaces) use preg_split().

<?php
echo json_encode(str_split("PHP")) . "<br>";
echo json_encode(preg_split("/\s+/", "one   two three"));
?>

Output:

Tutorials Class - Output Window

[“P”,”H”,”P”]
[“one”,”two”,”three”]

Learn more in PHP explode() Function.


Learn more about the similar topics:
Tutorials
PHP String Handling
PHP explode() Function
PHP strpos() Function
PHP implode() Function
Exercises & Assignments
Write a PHP program to reverse the string
Write a PHP program to find the length of the string
Write a PHP program to count the words in the string
Write a PHP program to convert a string into uppercase
Interview Questions & Answers
How will you concatenate two strings in PHP?
What is the difference between single quote and double quote string in PHP?
Why we use PHP String functions trim(), ltrim() and rtrim()?
What PHP Function is used to find position of a string?
What is the use of ucwords() PHP String function?
What is the use of str_replace() PHP String function?
How to find String Length in PHP?