PHP Function of the Day (2011-9-27): date_parse

One of the more popular functions in PHP is [fphp]strtotime[/fphp]. Occassionally I see it paired with date to find out a month or day. This is inefficient compared to using today’s function - [fphp]date_parse[/fphp]

Date parse returns an array about the date, or false if the date is invalid. As of PHP 5.4 you’ll be able to use array offsets on the return to grab the month, day or year immediately

<?php
// Example of offset access available as of PHP 5.4
$day = date_parse('2011-03-04')['day'];

date_parse() only parses the supplied date string into its component parts, it is not intended to do the same thing as date('...', strtotime('...')).

P.S. Your example won’t work, 'Today' contains no day part.

Fixed. That’s odd, the instructions imply it takes the same arguments as strtotime.

It does take the same input as strtotime, your mistake was in expecting the result to have all of the resultant array items populated according to the date calculated from the input string.

It doesn’t help that the only example in the manual provides all of the date/time parts in the input.

date_parse() is not very useful to me because I’m always needing the timestamp. I might use it more often if part of the returned array was the timestamp. But I guess that’s what strtotime is for. :wink: