Skip to content
PHP Logo

How can PHP be used to sort an HTML table by day of the week?

To sort an HTML table by day of the week using PHP, you can first extract the day of the week from the date in each row of the table. Then, you can use a sorting function in PHP to sort the rows based on the day of the week. Finally, you can output the sorted table with the rows arranged by the day of the week.

php
<?php
// Sample HTML table with dates
$html_table = '
<table>
  <tr><td>Monday, 12/20/2021</td></tr>
  <tr><td>Wednesday, 12/22/2021</td></tr>
  <tr><td>Friday, 12/24/2021</td></tr>
  <tr><td>Tuesday, 12/21/2021</td></tr>
  <tr><td>Thursday, 12/23/2021</td></tr>
</table>';

// Function to extract day of the week from date string
function getDayOfWeek($date) {
    $day = date('l', strtotime($date));
    return $day;
}

// Extract dates and sort by day of the week
$dates = [];
preg_match_all('/>([^<]+)<\/td>/', $html_table, $matches);
foreach ($matches[1] as $match) {
    $dates[] = $match;
}
usort($dates, function($a, $b) {
    return strtotime($a) - strtotime($b);
});

// Output sorted table
echo '<table>';
foreach ($dates as $date) {
    echo '<tr><td>' . $date . '</td></tr>';
}
echo '</table>';
?>