skip to Main Content

enter image description here

How do I create a table with a column of the current month’s dates in php using a foreach loop?

2

Answers


  1. <table>
      <thead>
        <tr>
          <th>Date</th>
        </tr>
      </thead>
      <tbody>
        <?php
          $m = date('m'); // current month
          $y = date('Y'); // current year
    
          foreach(range(1, date('t')) as $d) { 
        /* loop through each day in the current month */
            echo '<tr><td class="date">' . $y . '-' . $m . '-' . $d . '</td></tr>';
          }
        ?>
      </tbody>
    </table>
    
    Login or Signup to reply.
  2. <?php
    // Set the timezone to your preferred timezone
    date_default_timezone_set('UTC');
    
    // Get the current month and year
    $month = date('m');
    $year = date('Y');
    
    // Get the number of days in the current month
    $days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    
    // Create an array of dates in the current month
    $dates = array();
    for ($day = 1; $day <= $days_in_month; $day++) {
    $date = new DateTime("$year-$month-$day");
    $dates[] = $date->format('Y-m-d');
    }
    
    // Output the dates in an HTML table column
    echo "<table>";
    echo "<tr>";
    echo "<th>Dates</th>";
    echo "</tr>";
    foreach ($dates as $date) {
    echo "<tr>";
    echo "<td>$date</td>";
    echo "</tr>";
    }
    echo "</table>";
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search