Salam
Salam

Reputation: 3

PHP Trouble with day change

I have this code bellow it works fine but when the time hits 24 till 1 it doesn't work. I'm not sure why.

The code I have:

<?php
$h = date('G'); //set variable $h to the hour of the day
$d = date('w'); //set variable $d to the day of the week.
$year = date('Y'); //set variable $year to the current year
//G is the date key for hours in 24 format (not 12), with no leading 0s, like 02.
// MONDAY SCHEDULE
if ($d == 1 && $h >= 0 && $h < 4) $text= 'bob';
else if ($d == 1 && $h >= 22 && $h < 23) $text= 'adam';
else if ($d == 1 && $h >= 23 && $h < 24) $text= 'tina';
else if ($d == 2 && $h < 0) $img = 'mark';
// TUESDAY SCHEDULE
if ($d == 2 && $h >= 0 && $h < 4) $text= 'alex';
else if ($d == 2 && $h >= 4 && $h < 8) $text= 'jason';
else if ($d == 3 && $h < 0) $text= 'gorge';
print $text;
?>

When it's mark's or gorge's turns it doesn't work. I would like to know how to fix it. Any help would be appreciated.

Thank you

Upvotes: 0

Views: 50

Answers (1)

trincot
trincot

Reputation: 350280

Like stated in comments, the test on $h < 0 will always return false, as $h is an integer between 0 and 23.

But you could make your schedule more readable and manageable if you would create a data structure for it, like this:

mb_internal_encoding("UTF-8");

$persons = array(
    '-' => '(no one)',
    'a' => 'Bob',
    'b' => 'Adam',
    'c' => 'Tina',
    'd' => 'Marc',
    'e' => 'Alex',
    'f' => 'Jason',
    'g' => 'George'
);
$schedule = array(
//   012345678901234567890123
    '------------------------', // Sunday
    'aaaa------------------bc', // Monday
    'eeeeffff----------------', // Tuesday
    '------------------------', // Wednesday
    '------------------------', // Thursday
    '------------------------', // Friday
    '------------------------', // Saturday
);

// Use mb_substr to support multi-byte characters (unicode)    
print $persons[mb_substr($schedule[date('w')],date('G'),1)];

In the above code, each person gets a unique letter. That letter is used in a kind of grid, where each row represents a weekday, and each column (character position) an hour of the day (0-23).

This way you have a rather visual representation, which might be easier to manage. And as it turns out, to get the person that is scheduled for the current hour-slot just takes a single line of code.

Upvotes: 1

Related Questions