0

Format Dates:

$nonzero_task_date = array_map(function($values)
            {
                return date('d-m-Y', strtotime($values));
            }, $nonzero_task_date);

            $date_arr = array_map(function($value)
            {
                return date('d-m-Y', strtotime($value));
            }, $date_arr);

Date array:

print_r($date_arr);

    Array
(
    [0] => 13-04-2015
    [1] => 14-04-2015
    [2] => 15-04-2015
    [3] => 16-04-2015
    [4] => 17-04-2015
    [5] => 18-04-2015
    [6] => 19-04-2015
)

print_r($nonzero_task_date );

    Array
(
    [0] => 16-04-2015
    [1] => 14-04-2015
    [2] => 13-04-2015
    [3] => 16-04-2015
    [4] => 17-04-2015
)

foreach ($date_arr as $row) {
  //$format_date = new DateTime($row);
  //$date_format = $format_date->format('d-m-Y');

   //compare dates 
  if( (in_array($row, $nonzero_task_date)) ){
    $sql = 'update query';

  }
}

The above code formats the date, but fails when dates are compared using in_array()?

Also it slow down the sql process and takes time due to number of records in DB, if date formatted in foreach loop.

3
  • 1
    Firs of all, are you sure, that process is slow because of this code? It seems, like you are trying to prematurely optimize it without proper profiling. Commented Apr 17, 2015 at 5:53
  • Yes it gets slow when I format the date inside foreach. Formatting it before loop will help remove the unnecessary date formatting inside loop Commented Apr 17, 2015 at 5:55
  • So you are hoping to find a way format an array of dates without looping over the array? Commented Apr 17, 2015 at 5:57

1 Answer 1

2

If I understand correctly, you could use array_map to run a function over each array element before looping over it.

$date_arr = array_map(function($value)
{
    return date('d-m-Y', strtotime($value));
}, $date_arr);
Sign up to request clarification or add additional context in comments.

13 Comments

Jordan Doyle: is the code applicable before foreach loop ? and how its different from $format_date = new DateTime($row); $date_format = $format_date->format('d-m-Y'); ?
@Jordan What about array_walk() ? Can it be used in this case ?
@Slimshadddyyy the code will work before the foreach loop and there's really not much difference between strtotime and DateTime in this case except one less object to clean up.
@AwRak array_walk will work in this case but I prefer array_map due to it not passing in a reference making it more obvious in what it's doing.
@Slimshadddyyy code you've provided works for me. See it here in action ideone.com/DkqvEs
|

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.