Friday, January 4, 2013

PHP implode function

implode() Function

The implode function is used to join an elements of an array with a string.

The implode() function returns a string from elements of an array. It takes an array of strings and joins them together into one string using a delimiter (string to be used between the pieces) of your choice.

The implode function in PHP is easily remembered as "array to string", which simply means that it takes an array and returns a string. It rejoins any array elements and returns the resulting string, which may be put in a variable.

Let's take an example:

If you want to separate array values with a dashed (-), Following statement is just fine.

<?php

$array = array('XXX', 'TTT', '2123123');
$dash_separated = implode("-", $array);

var_dump($dash_separated);

It will output the result as follows :

string(15) "XXX-TTT-2123123"

Here are the tricky ways of implode will get naughty.

1) When try to implode with empty array.
eg:

<?php
//When using empty array it will return empty string even passed the glue 
var_dump(implode('hello', array()));


Above code will output empty string as :


string(0) ""


2) When try to implode with array with boolean.

eg:
<?php

//When imploding boolean values it will just return the values of true
var_dump(implode('',array(true, true, false, false, true)));



Above code will output only true(s) as :

string(3) "111"

Advanced usage of implode method

If you are dealing with sql functions the implode method is just perfect. try following codes:

<?php

//Quite handier with sql functions with arrays

$fields = array(
        'subject' => 'go green',
        'message' => 'i am going to take off!'
);

$sql = 'INSERT INTO table_name';
$sql .= " VALUES (`" . implode("`,`", array_keys($fields)) . "`)";
$sql .= " ('" . implode("','", $fields) . "')";

var_dump($sql);

$userIds = array(2, 32, 55, 200, 44);

$sql2 = "SELECT * FROM table_name";
$sql2 .= " WHERE 1 AND (id=" . implode(" OR id = ", $userIds) . ")";

var_dump($sql2);



Above codes will give the output as follows:


string(90) "INSERT INTO table_name VALUES (`subject`,`message`) ('go green','i am going to take off!')"
string(88) "SELECT * FROM table_name WHERE 1 AND (id=2 OR id = 32 OR id = 55 OR id = 200 OR id = 44)"

Happy coding ~