Using PHP implode() To Construct Strings

4th June 2009

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. $array = array(1, 2, 3, 4, 5, 6);
  2.  
  3. 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.

  1. $sql = 'SELECT * FROM table';
  2.  
  3. $clauses = array();
  4. //These two variables might be created via a form request.
  5. $column1 = 'one';
  6. $column2 = 'two';
  7.  
  8. if ( isset($column1) ) {
  9. $clauses[] = 'column1 = "'.$column1.'"';
  10. }
  11. if ( isset($column2) ) {
  12. $clauses[] = 'column2 = "'.$column2.'"';
  13. }
  14.  
  15. if ( count($clauses) > 0 ) {
  16. $sql .= ' WHERE '.implode(' AND ', $clauses).';';
  17. }
  18. 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

Permalink

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

Submitted by Krrish on Tue, 09/13/2011 - 12:03

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

Submitted by Gossip Lanka on Tue, 09/29/2015 - 20:28

Add new comment

The content of this field is kept private and will not be shown publicly.