- HubPages»
- Technology»
- Computers & Software»
- Computer Science & Programming»
- Programming Languages
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 );
Useful PHP Tutorial
- Learn About PHP function syntax
In this PHP Tutorial, I'll explain some of the basics about PHP function Syntax (or I say syntax of PHP function), Which one should have in understanding it without any confusion.
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 ?
Important Note
- "PHP Implode function" join all elements/pieces of array in original order and you cant limit it to shorter range.