Today tutorial, we will share with you the way to convert a PHP string into array. we will convert a string into array in PHP by specify character. You will learn how to convert a text to an array using a delimiter in PHP. By just follow the simple steps below to learn how to trun an array from a text in PHP.
we are going to use explode()
function to convert an string to an array with a delimiter which means we break a string into piece of array element. We'll give you two examples below so that you will understand how it works.
explode() - split string data into elements of array using a separator or delimiter.
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
Return Value: Returns array of string. Result from a string splited by separator.
Parameter | Type | Description |
---|---|---|
$separator |
String (Required) | Specifies where to split the string. |
$string |
String (Required) | String to be splitted by separator. |
$limit |
Integer (Optional) | Specifies the element number of array to return after splitted. |
Also Read
Example #1
<?php
$cakes = "Pie1 Pie2 Pie3 Pie4 Pie5 Pie6";
$string = explode(' ', $cakes);
echo '<pre>' , var_dump($string) , '</pre>';
?>
Output:
array(6) { [0]=> string(4) "Pie1" [1]=> string(4) "Pie2" [2]=> string(4) "Pie3" [3]=> string(4) "Pie4" [4]=> string(4) "Pie5" [5]=> string(4) "Pie6" }
Example #2
<?php
$cakes = "Pie1-Pie2-Pie3-Pie4-Pie5-Pie6";
// Positive limit, return 3 elements array
$exp1= explode('-', $cakes, 3);
// Negative limit, remove last 2 elements array
$exp2= explode('-', $cakes, -2);
echo '$exp1 output: <pre>', var_dump($exp1),'</pre>';
echo '$exp2 output: <pre>', var_dump($exp2),'</pre>';
?>
Output:
$exp1 output: array(3) { [0]=> string(4) "Pie1" [1]=> string(4) "Pie2" [2]=> string(19) "Pie3-Pie4-Pie5-Pie6" } $exp2 output: array(4) { [0]=> string(4) "Pie1" [1]=> string(4) "Pie2" [2]=> string(4) "Pie3" [3]=> string(4) "Pie4" }
I hope you will learn and how to use this function.
PHPFounder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him