Convert a String to Array in PHP

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.

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);
?>

Demo

How to Remove Duplicate Values from an array with PHP PHP Sort Associative array by Key PHP Sort Associative array by Value Sort array in numerical order with PHP Sort array in alphabetical order with PHP Sort array in descending order PHP Sort array in ascending order in PHP How to merge two or more arrays in PHP Add elements to the end of an array in PHP Add elements to the start of an array in PHP PHP Remove First Element from an Array PHP Remove Last Element from an Array Check if Key Exists in array PHP Check if Value exists in array PHP How to reverse an array in PHP PHP Print array line by line PHP Echo array values using foreach loop Count array values in PHP PHP Count How Many Times Word appears in String How to Reverse a String with PHP Check if Variable is Null in PHP Check if Variable is Empty in PHP Check if Variable is Set or Not PHP Create New Line in PHP Remove Spaces from End of a String in PHP