Geronimo89.dk

A blog about me, my doings and everything I think deserves attention.

PHP explode and implode

I think PHP is one of the few place where you can explode and implode without being a terrorist but still have fun with it. At least explode() is one of my favourite functions in PHP :).

For this little quick tip I actually have a quite practical use case I stumbled upon a couple of days ago. The jQueryUI datepicker widget. It lets the user pick a date, which you automatically can insert into a form. You can define different formats like day day, month month, year year and so on, whatever makes you happy, but to save it in a MySQL database you might want to convert it to the typical yyyy-mm-dd format. For that we spread the string we pull from the form at 2 different places (where the datepicker sets the slashes).

explode()

Exploding may sound a little extreme in the beginning, but it’s just a function to split a string into an array at certain points.

$explodeable = '28/05/2011';
$exploded = explode('/',$explodeable);
print_r($exploded);

// generates output:

Array ( [0] => 28 [1] => 05 [2] => 2011 )

implode()

Now, we still have to get the year, month and day together again to put it in a MySQL DATE or DATETIME field, so let’s look at the solutions we have for that with implode. Implode just puts a string together from an array with or without a certain character between them.

$exploded = array_reverse($exploded);
print_r($exploded);

// generates output:
Array ( [0] => 2011 [1] => 05 [2] => 28 )

$imploded = implode('-', $exploded);
echo $imploded

// generates output:
2011-05-28

For this it works perfectly, but you can also chain the different values of an array as following, if array_reverse can’t do the job and you want to sort your entries manually. This solution gives you more flexibility, also with the characters in between the split values.

$chained = $exploded[2].'-'.$exploded[1].'-'.$exploded[0];
echo chained;

// generates output:
2011-05-28

Thanks for reading my little quick tip on date conversion between the jQueryUI and MySQL, have a nice time everybody icon smile PHP explode and implode

Only 1 comment so far

One Response to “PHP explode and implode”

  1. The benefits I personally draw from it are primarily that you can define a range of dates in your queries and that you always have a steady format to work from, that you can change in a simple way to output it otherwise.

Leave a Reply