How to Convert a String Into an Array in PHP
-
Convert a String Into an Array Using the
explode()
Function in PHP -
Convert a String Into an Array Using the
str_split()
Function in PHP
PHP is a powerful scripting language, and it provides us with many in-built solutions to convert a string into an array by using its built-in functions that can be used for different requirements. This tutorial will discuss using PHP to convert a string to an array.
Convert a String Into an Array Using the explode()
Function in PHP
Let’s imagine we have a string list of fruits, and we want to convert it into an array. The explode()
function is used in the code example below.
The explode()
function is a PHP method used to convert a string into an array. The function uses a separator or a delimiter that needs to be passed as an argument, and it takes in 2 arguments, the first one is a delimiter and the second one is a string.
Code:
<?php
$string = "Apple, Banana, Pineapple, Orange";
$converted = explode(", ", $string);
print_r($converted);
Output:
Convert a String Into an Array Using the str_split()
Function in PHP
Suppose we want to convert a string into an array so that each letter from a string is stored separately. We can achieve this scenario using the function str_split()
.
This function will convert a string into an array by breaking the string into small substrings. We can define the length of the substrings, and it doesn’t need a separator or a delimiter.
Code:
<?php
$str = "This is a string";
$newStr = str_split($str, 1);
print_r($newStr);
Output:
In the last example, we want to separate the string into an array that breaks down after 3 letters instead of separating each letter.
Code:
<?php
$str = "This is a string";
$newStr = str_split($str, 3);
print_r($newStr);
Output:
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedInRelated Article - PHP String
- How to Remove All Spaces Out of a String in PHP
- How to Convert DateTime to String in PHP
- How to Convert String to Date and Date-Time in PHP
- How to Convert an Integer Into a String in PHP
- How to Convert an Array to a String in PHP
- How to Convert a String to a Number in PHP