In this tutorial we will learn How To Convert a String to Array in PHP. A string is generally made of many words and we can split it into parts to form one array with many values.
Table of Contents
PHP explode() Function
PHP explode() Function returns an array from the string by breaking it into small parts as values of array.
In this example we can use PHP explode() Function to convert our string into an array. Separator is always defined to tell where to break the string.
Take a look at the code given below.
<?php
$string = "How To Code School";
$array = explode(" ",$string);
print_r ($array);
?>
The above code will break the string after every space and will convert 'How To Code School' into an array with four different values because there are four different words in this string.
PHP str_split() Function
PHP str_split() Function also splits the string into an array.
str_split() function converts the string to array without delimiter. The length of each value of array depends on the length defined in str_split() function.
By default length is 1 which means it will break the string after every character to form the array.
<?php
$string = "How To Code School";
$array = str_split($string);
print_r ($array);
?>