It uses the str_split() method to convert the string to an array. In the above example, it initializes a variable $my_string1 with a string “Sample String”. Print_r($my_array2) // sam, ple, str, ing The following example illustrates the working of the str_split() function to convert string to array in PHP.Įcho "The array of length 3 elements is: " If the length that is passed to the function surpasses the length of the initial string, the function will return the whole string as one element, whereas if the length integer is less than one, the function will return false. This function returns an array that contains the pieces of the original string. If not passed, the function will consider this length as 1 by default.
#PHP JSON DECODE INTO ARRAY MANUAL#
There are various approaches, including in-built functions and manual approaches that are used to convert string to array in PHP. This article explains several approaches to achieve this task.įollowing is the complete list of methods that can be used in PHP to convert a string to an array.ĭifferent Methods to Convert String to Array in PHP Being a powerful scripting language, PHP provides various in-built methods to convert a string to an array.
When you convert a string into an array, it makes data manipulation convenient. Arrays can help you implement better data organization and faster operations. This provides more security and ease of access to the data. For instance, you can convert the passwords entered as input in a web application into an array before storing them in the database. There are many cases when an array is considered more suitable over a string. Why Do You Need to Convert a String to an Array in PHP?