Using PHP implode() To Construct Strings

Thursday, June 4, 2009 - 10:33

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.

1
2
3
$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.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$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;

This will print out the following:

1
<p>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.</p>
Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

Add new comment