PHP code for concatenating array elements to string with delimiters

As in the earlier concatenating array elements into string with delimiter are quite complex. Now it is  easy to concatenate the  array elements to string with delimiter using PHP implode() or join().

1. implode()

implode() joins the array elements into string.

SYNTAX:

string implode ( string $delimiter, array $arrayelements )

$delimiter – value that separates the array elements (optional)

$arrayelements – array of string elements

EXAMPLE:

<?php
$arrayelements=array("Learn","Web","Development");
$string=implode(" ",$arrayelements);
echo $string;
?>

OUTPUT:

Learn Web Development

2. join()

join() is an alias of implode().

SYNTAX:

string join( string $delimiter , array $arrayelements )

$delimiter– value that separates the array elements (optional)

$arrayelements – array of string elements

EXAMPLE:

<?php
$arrayelements=array("Learn","Web","Development");
$string=join("*",$arrayelements);
echo $string;
?>

OUTPUT:

Learn*Web*Development

3.explode()

explode() splits the string into array elements.

SYNTAX:

string explode( string $delimiter , array $arrayelements ,int $limit)

$delimiter – value that separates the array elements

$arrayelements – array of string elements

$limit – specifies the number of elements to be returned (optional)

EXAMPLE:

<?php
$arrayelements=array("Learn","Web","Development");
$string=join("*",$arrayelements);
$explodestring=explode("*",$string,3);
print_r($explodestring);
?>

OUTPUT:

Array ( [0] => Learn [1] => Web [2] => Development )

If limit value is 2 then output will be

Array ( [0] => Learn [1] => Web*Development )

Posted in Php Tagged with: ,