Home > Net >  How to echo the current day from an array of days?
How to echo the current day from an array of days?

Time:12-17

<html>
    <body>
    <?php  
    $days = array("Monday", "Tuesday", "Wednesday", "Thursday" ,"Friday" ,"Saturday" ,"Sunday"); 

    foreach ($days as $value) {
      echo "
      <button type='button' class='btn btn-primary'>$value</button>";
    }
    ?> 
    <h1  style="text-align: center;color:black ">Today is <?php echo "$value"; ?></h1> 

    </body>
</html>

CodePudding user response:

In order to access the current day of the week, php provides a function called date()

Which the documentation can be found here: https://www.php.net/manual/en/function.date.php

As for your code, You can mention all of the days, however the system would not know the day simply from an array. It would need to access the current time. You can do this by modifying your code as such.

<html>
    <body>
    <?php  
    $days = array("Monday", "Tuesday", "Wednesday", "Thursday" ,"Friday" ,"Saturday" ,"Sunday"); 

    foreach ($days as $value) {
      echo "
      <button type='button' class='btn btn-primary'>$value</button>";
    }
    ?> 
    <h1  style="text-align: center;color:black ">Today is <?php echo date('l'); ?></h1> 

    </body>
</html>

However since you seem to be using a button, some might believe that you're expecting to display the value clicked.

Please update your question if that is the case. Otherwise this code will always display the current day of the server.

CodePudding user response:

I think This Should be Your Solution if you make days arrays as indexed array as below

<html>
    <body>
    <?php  
    $today = "";
    $days = array(
        1 => "Monday",
        2 => "Tuesday",
        3 =>  "Wednesday",
        4 => "Thursday",
        5 => "Friday",
        6 => "Saturday",
        7 => "Sunday"
    ); 

    foreach ($days as $key=>$value) {
        if(date('N')==$key){
            $today = $value;
            echo "<button type='button' style='background: red'>$value</button>";
        }else{
            echo "<button type='button'>$value</button>";
        }
    }
    ?> 
    <h1  style="text-align: center;color:black ">Today is <?php echo "$today"; ?></h1> 

    </body>
</html>

  • Related