Categories
PHP

Explode and Implode Functions

Learn how to convert arrays into strings and strings into arrays with the help of two PHP functions implode() and explode().

Split a string based on a delimiter

Sometimes, arrays are not used to store information; instead, a string is used. The single values are all within the string but are separated by a special character. See the following example, splitting text based on new-line characters:

<?php
/* Explode Syntax 
array explode (string $delimiter, string $string[,int $limit])
*/
 $string = "House No.\nStreet Name\nCity\nCountry";
 $array  = explode("\n", $string);

explode function splits a string by a delimiter and returns an array of strings. This function accepts three parameters:

  1. delimiter a boundary string
  2. string an input string
  3. limit maximum of limit elements with the last element containing the rest of the string

Convert CSV text into an array

<?php
  $csvdata = 'value 1,value 2,value 3,value 4,value 5';
  $a = explode(',', $csvdata);
  
  $info = print_r($a, true);
  echo "<pre>$info</pre>";

  foreach ($a as $value) {
   echo $value . '<br>';
  }

The PHP function explode() creates an array out of these values; you just have to provide the character(s) at which the string needs to be split. The browser then shows this output:

//print_r result
Array
(
    [0] => value 1
    [1] => value 2
    [2] => value 3
    [3] => value 4
    [4] => value 5
)

//foreach result
value 1
value 2
value 3
value 4
value 5

The implode function

/*
Syntax
string implode ( string $glue , array $pieces )
*/
$string = implode(",", $array);

In the above example, PHP joins the elements of the array, using the comma , character. This function accepts two parameters:

  1. glue
    Any string value to join with i.e dot ., comma ;, html tag <br> or any character.
  2. array
    The input (array) of strings to implode.

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

Turning an Array into a String

<?php
  $data = array('PHP','MySQL','JS','CSS');
  $string = implode(' - ', $data);
  echo $string;

  /*prints:
  PHP - MySQL - JS - CSS
  */

Working with arrays:

  1. Creating Arrays
  2. Array Iteration
  3. Array Internal Pointers
  4. Explode and Implode Functions
  5. Count Array Elements, Find Min and Max Values
  6. Search values and keys in arrays
  7. Filter array elements using array_filter()
  8. Modify array elements using array_map() and array_walk()
  9. Split, tokenize, and iterate a string
  10. Convert a delimited string into an array
  11. Sorting arrays