Skip to content

Instantly share code, notes, and snippets.

@zeraphie
Created March 8, 2016 15:32
Show Gist options
  • Save zeraphie/06119f0908244e893c54 to your computer and use it in GitHub Desktop.
Save zeraphie/06119f0908244e893c54 to your computer and use it in GitHub Desktop.
Get today's item from a list of items
function todays_item($arr){
$count = count($arr);
$number = floor(time() / 86400) % $count;
return $arr[$number];
}
$arr = array(
'One',
'Two',
'Three'
);
echo todays_item($arr);
@zeraphie
Copy link
Author

zeraphie commented Mar 8, 2016

Takes any length array and returns the current day's item from the array, such as a quote of the day from a ordered list of quotes

@zeraphie
Copy link
Author

zeraphie commented Jan 13, 2017

/**
 * Javascript version - http://codepen.io/zephyr/pen/2b75618cf51457b5365235f052f8554b?editors=0010
 */

/**
 * Get the item of the array that corresponds to today
 *
 * Note: Useful in cases like a quote of the day where there are a set amount of quotes to be used
 *
 * Gets the current timestamp in seconds and divides it by the number of seconds in a day
 * then takes the modulus of that in comparison to the array length to make the selection
 *
 * @param arr The array to search through
 *
 * @return mixed The current day's item in the array
 *
 */
let getTodaysItem = (arr) => {
    return arr[(Math.floor(Math.floor(Date.now() / 1000) / 86400)) % arr.length];
}

// Fill a test array with 80 items
let test = [];

for(let i = 0; i < 80; i++){
    test.push(i);
}

// Log the test array
console.log(test);

// Get today's item from that array
console.log(getTodaysItem(test));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment