Little bug in the foreach
foreach ($i = 0; $i < $#entries; $i++)
should be
foreach ($i = 0; $i < $#entries+1; $i++)