Why would a function that returns an incorrect array ordering return the expected ordering when I call print_r()
or var_dump()
on the array just before sorting?
I'm trying to print basic info about the next few events collected from several Google calendars, sorted by a custom uasort()
based on the event start date/time.
function getUpcomingEvents()
{
$calUrls = array( /* Four Google calendar URLs */);
foreach ($calUrls as $url)
{
$calEvents = json_decode(file_get_contents($url), true);
for($i=0; $i<count($calEvents['items']); $i++)
{
$item = $calEvents['items'][$i];
$events[] = array(
'title' => $item['summary'],
'description' => $item['description'],
'start' => date_create($item['start']['dateTime']),
'end' => date_create($item['end']['dateTime']),
'htmlLink' => $item['htmlLink']
);
}
}
//print_r($events); // <-- **LOOK AT ME**
uasort($events, function($a, $b) {
return strtotime($a['start']->date) - strtotime($b['start']->date);
});
return $events;
}
...*snip*...
<?php foreach(getUpcomingEvents() as $event) : ?>
<li><h3><?php echo date_format($event['start'], 'M j'); ?></li>
<?php endforeach; ?>
When I load the page with print_r() commented out this way, my list items print out in this order:
Feb 19, Feb 21, Feb 23, Feb 26, Mar 5, Feb 19, Feb 16,...
(Note: these represent events from calendars 1, 2, 1, 1, 1, 2, 2,..., respectively, so it doesn't simply reflect the order of the calendar requests.)
After uncommenting the print_r()
(with no other changes), the list items print ordered chronologically:
Feb 10, Feb 14, Feb 16, Feb 16, Feb 16, Feb 19, Feb 19,...
(Note: these are the printed <li>'s
, not the output of print_r()
itself, which is not sorted).
I Have Tried:
* declaring global $events;
above getUpcomingEvents()
in case it was a variable scoping issue
* using usort
instead of uasort
, and a separated comparison function declaration instead of an anonymous one
* building up $events
as an explicitly indexed array ($events[$i] = ...
) instead of using the []
operator in case that would help maintain a more stable array order
* assigning getUpcomingEvents()
to a new variable before passing it into the foreach
Is variable inspection really affecting my sorting or have I gone wrong somewhere else?
No, print_r does not affect your array. It just shows you the information of the variable.
From PHP page
print_r — Prints human-readable information about a variable