PHP Implode and explode example
PHP implode and explode Functions
Table of Contents
In this article, we are going to learn about Array Implode and explode usage using PHP. These are the most useful functions in PHP, which are used in array and string conversions. To perform these conversions, PHP provided 2 inbuilt functions called implode() and explode().
Implode : Combines all array elements into one string using specified separator and returns it.
Explode: Separates string into array elements according to the used separator in the string and return an array.
explode Function in PHP:
Syntax:
explode(separator, string)
Example:
$colors= "red,green,blue,pink" ;
$fruits_array = explode(",", $colors);
menu-top
explode function, takes two parameters, one is the separator and string.
explode, breaks the string into an array.
Code Example:
<?php
$fruits= "orange,mango,banana,apple" ;
$fruits_array = explode(",", $fruits);
print_r($fruits_array);
?>
output:
Array ( [0] => orance [1] => mango [2] => banana [3] => apple )
top-menu
Example2 : Here is another example of explode where separator is ':' is used.
It is one time string. Firstly it splits and then extract the Hours values.
<?php
$time = "13:30:00";
$time_array= explode (":" , $time);
print "<br>Hours= ".$time_array[0];
?>
implode Function:
Syntax:
implode(separator, array)
gotomenu
- Implode takes two parameters, separator and array name.
- Separator can be any other symbol like space ' ', pipe '|', semicolon ';', colon ':' etc.
- Second parameter is the array name that you want to combine.
Example
<?php
$fruits_array = array(orange, mango, banana, apple) ;
$string= implode("," , $fruits_array);
print $string ;
?>
implode Associative Array
move-up
The following function will take an associative array and return a string of array values.
<?php
function array_implode($sep, $arr) {
return is_array($arr) ?
implode($sep, array_map(__FUNCTION__, array_fill(0, count($arr), $sep), $arr)) :
$arr;
}
$assoc-arr = array( "1"=> "a", "2" => "b", "3" => "c");
echo array_implode(',', $assoc-arr);
?>
Result:
a,b,c
menu↑
implode Multidimensional Array
The same above function will convert multidimensional array and return string of array values.
<?php
function array_implode($sep, $arr) {
return is_array($arr) ?
implode($sep, array_map(__FUNCTION__, array_fill(0, count($arr), $sep), $arr)) :
$arr;
}
$Products = array ( "Category1" => array("Product1", "Product2", "Product3"), "Category2" => array("Product4"), "Category3" => array("Product5", "Product6", "Product7") );
echo array_implode(',', $Products );
?>
Result:
Product1,Product2,Product3,Product4,Product5,Product6,Product7
Comments
Post a Comment