PHP - Converting Between Arrays and Strings

Introduction

To convert a string to an array, use PHP's handy explode() string function.

This function takes a string, splits it into separate chunks based on a specified delimiter string, and returns an array containing the chunks.

Here's an example:

$fruitString  ="apple,pear,banana,strawberry,peach";
$fruitArray = explode(",", $fruitString);

Here, $fruitArray contains an array with five string elements: "apple", "pear", "banana", "strawberry", and "peach".

You can limit the number of elements in the returned array with a third parameter, in which case the last array element contains the whole rest of the string:

 Code:
 <?php
 $fruitString ="apple,pear,banana,strawberry,peach";
 $fruitArray = explode(",", $fruitString, 3);
 echo $fruitArray;
 ?>

Result

Here, $fruitArray contains the elements "apple", "pear", and "banana,strawberry,peach".

Alternatively, specify a negative third parameter to exclude that many components at the end of the string from the array.

For example, using 3 in the example creates an array containing just "apple" and "pear".

implode()

To put array elements together into one long string, use implode() function.

This takes two arguments:

  • the string of characters to place between each element in the string, and
  • the array containing the elements to place in the string.

The following code joins the elements in $fruitArray together to form one long string, $fruitString, with each element separated by a comma:

Demo

<?php
$fruitArray  = array("apple","pear","banana","strawberry","peach");
$fruitString = implode(",", $fruitArray);
echo $fruitString;/*from w  w w  .  java2s  .com*/
?>

Result

Related Topic