Skip to content

Instantly share code, notes, and snippets.

@barryhughes
Created March 2, 2021 18:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barryhughes/ebcd0dee402e7db8abf9f0a969ff3d74 to your computer and use it in GitHub Desktop.
Save barryhughes/ebcd0dee402e7db8abf9f0a969ff3d74 to your computer and use it in GitHub Desktop.
Get a random fact.
<?php
/**
* Get a string containing a random fact.
*
* If a random fact cannot be fetched from the external service, a default is
* supplied instead.
*
* @return string
*/
function get_random_fact(): string {
$fact_payload = file_get_contents( 'https://uselessfacts.jsph.pl/random.json' );
if ( $fact_payload ) {
$fact_data = json_decode( $fact_payload );
}
return ( is_object( $fact_data ) && property_exists( $fact_data, 'text') )
? $fact_data->text
: 'A ton of feathers weighs just as much as a ton of bricks.';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment