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).
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 (  => 28  => 05  => 2011 )
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 (  => 2011  => 05  => 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.'-'.$exploded.'-'.$exploded; 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