PHP Tutorial: How to use PHP implode function

Introduction

Here, I'm Publishing Some information on "PHP Implode Function" which simplifies our Task of Merging pieces of any array into one Value with or without any glue/delimiter (separator). This Function can be considered as an reverse solution of "PHP explode function" because its need arises mostly after creating and populating an array. "Populating an array" means adding new entries/elements/indexes in array. Well, PHP explode function creates and populate arrays automatically by using our delimiter (separator) specified in its parameter on any string.

In Syntax shown below, "$glue" parameter is optional i.e. you are free to not use this parameter while implementing "Implode" function in your scripts.

Syntax of PHP Implode Function

string implode ( string $glue , array $pieces );

Official Documented Note

implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.

Function Output (Returns)

This function outputs the result in the form of string after merging all elements/pieces of array together in the same order with an glue attached between all elements.


Simple Example Showing Usage of PHP Implode Function

<?php

$myarray = array('car', 'bike', 'truck');
$implode_myarray = implode(", ", $myarray);

echo $implode_myarray; 

/*About PHP statement will 
output this without double quotes
i.e. "car, bike, truck" on Screen */
?> 

PHP Implode (Recursive) Usage in Multidimensional Array

<?php 

function r_implode( $glue, $pieces ) 
{ 
  foreach( $pieces as $r_pieces ) 
  { 
    if( is_array( $r_pieces ) ) 
    { 
      $retVal[] = r_implode( $glue, $r_pieces ); 
    } 
    else 
    { 
      $retVal[] = $r_pieces; 
    } 
  } 
  return implode( $glue, $retVal ); 
} 

$test_arr = array( 0, 1, array( 'a', 'b' ), array( array( 'x', 'y'), 'z' ) ); 
echo r_implode( ',', $test_arr ) . "\n"; 
?>

What Do You Think About this Article ?

  • Helpful
  • Need Revision
  • Lacks Information
  • Less Examples
  • COnFuSed
  • I'd like to see more options in this poll
See results without voting

Important Note

  • "PHP Implode function" join all elements/pieces of array in original order and you cant limit it to shorter range.

More by this Author


Comments 2 comments

linel 5 years ago

i cant uderstand this code


itech profile image

itech 5 years ago from New Delhi, India Author

@linel, is it second one (Multidimensional) or first one.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working