gazdac
gazdac

Reputation: 189

PHP strtotime bug?

Take a look at this code and please tell me how is it possible that this works flawlessly for Wednesday, but not for Tuesday:

 <?php
$current_time = strtotime('now');
if ($current_time > strtotime('tuesday this week 8:45pm') && $current_time < strtotime('tuesday this week 11:45pm')) {
 $background = 1;
}
if ($current_time > strtotime('wednesday this week 8:45pm') && $current_time < strtotime('wednesday this week 11:45pm')) {
 $background = 1;
}
else{
$background = 0;
}

?>

   <script>
   var backday = <?php echo json_encode($background); ?>;
   </script>

For Tuesday, it returns 0, but for Wednesday it returns 1, as it should. WHY?

Upvotes: 0

Views: 296

Answers (1)

Revent
Revent

Reputation: 2109

You have an error in your logic. The first conditional might return 1, but then you hit your second conditional. If that first if in the second conditional is false, it will set the variable to 0 in your else block regardless of what it was set to in your first conditional. You need to make your second if statement an else if like this:

 if ($current_time > strtotime('tuesday this week 8:45pm') && $current_time <   strtotime('tuesday this week 11:45pm')) {
    $background = 1;
}
else if ($current_time > strtotime('wednesday this week 8:45pm') && $current_time < strtotime('wednesday this week 11:45pm')) {
   $background = 1;
}
else{
   $background = 0;
}

Upvotes: 3

Related Questions