Using PHP implode() To Construct Strings

If you are constructing a simple string from a set of variables contained in an array then you can use the implode function to convert the array into a string. The implode() function takes two parameters. The first is the glue that is used to join the items in array together and the second is the array to use. Here is a trivial example of implode() in action.

$array = array(1, 2, 3, 4, 5, 6);
 
echo implode(',', $array);

This will print out the following:

1,2,3,4,5,6

The good thing about the implode() function is that it doesn't add stray commas to the start and end of the string so there is no need to alter the string after the function is used.

$sql = 'SELECT * FROM table';
 
$clauses = array();
 //These two variables might be created via a form request.
$column1 = 'one';
$column2 = 'two';
 
if ( isset($column1) ) {
    $clauses[] = 'column1 = "'.$column1.'"';
}
if ( isset($column2) ) {
    $clauses[] = 'column2 = "'.$column2.'"';
}
 
if ( count($clauses) > 0 ) {
    $sql .= ' WHERE '.implode(' AND ', $clauses).';';
}
echo $sql;

So how can this function be used in any application? If you are creating an SQL statement then you can use implode to construct it through an array. The following code will take two variables called $column1 and $column2 and use them to create the WHERE clause of an SQL statement. The two variables might be created through GET or POST requests but the string for each clause is added to an array called $clauses. At the end of this process, if the array length is greater than 1, the implode() function is used to add the full WHERE clause to the SELECT statement.

This will print out the following:

SELECT * FROM table WHERE column1 = "one" AND column2 = "two";

This might not be applicable for all applications, but I think it makes SQL statement creation slightly more readable than constructing them purely as strings.

Comments

Never thought of using implode function in such way.... Useful Example.

Permalink
Great article. this is exactly i was looking. thanks again
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
11 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.