How to Convert PHP String into Array?

Sovary May 27, 2022 476
1 minute read

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.

Syntax

explode(string $separator, string $string, int $limit = PHP_INT_MAX): array

Return Value: Returns array of string. Result from a string splited by separator.

Parameters

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

Examples

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.

PHP 
Author

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him