phparraysdatetimesanitizationtruncation

Remove time expressions from a flat array of datetime strings


I was wondering is it possible to convert the following array:

Array (
    "2016-03-03 19:17:59",
    "2016-03-03 19:20:54",
    "2016-05-03 19:12:37"
)

Into this:

Array (
    "2016-03-03",
    "2016-03-03",
    "2016-05-03"
)

Without creating any loops?


Solution

  • There's no explicit loops, if you can use array_map, although internally it loops:

    function format_date($val) {
      $v = explode(" ", $val);
      return $v[0];
    }
    $arr = array_map("format_date", $arr);
    

    From the PHP Manual:

    array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map().

    Also, when you are dealing with Dates, the right way to do is as follows:

    return date("Y-m-d", strtotime($val));
    

    The simple way, using loops is to use a foreach():

    foreach($arr as $key => $date)
      $arr[$key] = date("Y-m-d", strtotime($date));
    

    This is the most simplest looping way I can think of considering the index to be anything.


    Input:

    <?php
    $arr = array(
        "2016-03-03 19:17:59",
        "2016-03-03 19:20:54",
        "2016-05-03 19:12:37"
    );
    function format_date($val) {
      $v = explode(" ", $val);
      return $v[0];
    }
    $arr = array_map("format_date", $arr);
    
    print_r($arr);
    

    Output

    Array
    (
        [0] => 2016-03-03
        [1] => 2016-03-03
        [2] => 2016-05-03
    )
    

    Demo: http://ideone.com/r9AyYV