1

I want to explode a date but want to rename default index 0,1,2 to year, month, day respectively, I tried but I am not able to figure it out. Here's what am doing right now.

$explode_date = explode("-", "2012-09-28");
echo $explode_date[0]; //Output is 2012
echo $explode_date[1]; //Output is 09
echo $explode_date[2]; //Output is 28

what I want

echo $explode_date['year']; //Output is 2012
echo $explode_date['month']; //Output is 09
echo $explode_date['day']; //Output is 28

Thanks..

WolvDev
  • 3,182
  • 1
  • 17
  • 32
Random Guy
  • 2,878
  • 5
  • 20
  • 32
  • Possible duplicate: http://stackoverflow.com/questions/240660/in-php-how-do-you-change-the-key-of-an-array-element – Stan Jul 13 '12 at 09:12
  • @V413HAV You might want to check out PHP's DateTime class (built-in) since it can handle dates and times gracefully. It's also supported by PHP, so why not use something that's already been built, rather than re-inventing the wheel? – Stegrex Jul 13 '12 at 09:25
  • @Stegrex As I told complex857 I need a solution for php version < 5 and by the way am not that good with OOP ;) still need to learn it. – Random Guy Jul 13 '12 at 09:29

6 Answers6

6
list($date['year'], $date['month'], $date['day']) = explode('-', '2012-09-28');

http://php.net/list

deceze
  • 510,633
  • 85
  • 743
  • 889
6

use array_combine:

$keys = array('year', 'month', 'day');
$values = explode("-", "2012-09-28");
$dates = array_combine($keys, $values);
complex857
  • 20,425
  • 6
  • 51
  • 54
  • Great 1, so +1 for this, its easy but I want php version < php5, so far @GordonM's answer suits my requirement. P.S Many have answered almost same like Gordon – Random Guy Jul 13 '12 at 09:22
1
list($year, $month, $day)  = explode("-", "2012-09-28");
$x = compact('year', 'month', 'day');


var_dump($x);
array
  'year' => string '2012' (length=4)
  'month' => string '09' (length=2)
  'day' => string '28' (length=2)
0
$explode_date = array (
    'year' => $explode_date [0],
    'month' => $explode_date [1],
    'day' => $explode_date [2]
);
GordonM
  • 31,179
  • 15
  • 87
  • 129
0
$explode_date = array();
list($explode_date['year'],$explode_date['month'],$explode_date['day']) = explode("-", "2012-09-28");

var_dump($explode_date);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

You'll have to map out the associations:

$explode_date = explode("-", "2012-09-28");
$new_array['year'] = $explode_date[0];
$new_array['month'] = $explode_date[1];
$new_array['day'] = $explode_date[2];

Or, you can use PHP's built in DateTime class (probably better since what you want to do has already been done):

http://www.php.net/manual/en/book.datetime.php

$date = new DateTime('2012-09-28');
echo $date->format('Y');
echo $date->format('m');
echo $date->format('d');
Stegrex
  • 4,004
  • 1
  • 17
  • 19