0

What is a better way of doing the the below. Is there some function where i can specify/add keys to my array while splitting

<?php
     $str = '2014-02-01';
     $darray = explode('-',$str);
     $final_array = array(
                     'year' => $darray[0],
                     'month' => $darray[1],
                     'day' => $darray[2],
     );
?>
3
  • Ideally, you should not do this. Splitting the date string could cause troubles down the road (i.e. when the format changes from Y-m-d to, say d-m-Y). Use DateTime class to create a DateTime object, and use that to get the year, month, and day. Commented Jun 16, 2014 at 17:55
  • @AmalMurali some link or sample code Commented Jun 17, 2014 at 16:53
  • Something like: $date = strtotime($str); $final_array['day'] = date('d', $date); Commented Jun 17, 2014 at 16:56

2 Answers 2

3

Here's one:

$final_array = array_combine(array('year','month','day'), explode('-',$str));
Sign up to request clarification or add additional context in comments.

Comments

1

You can use list():

$array = array();
list($array['year'], $array['month'], $array['day']) = explode('-', $str);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.