Skip to content

Instantly share code, notes, and snippets.

@sfrench
Forked from EnragedSuccubus/validate_int.php
Last active August 29, 2015 14:04
Show Gist options
  • Save sfrench/f3efb25ebf2f458923fb to your computer and use it in GitHub Desktop.
Save sfrench/f3efb25ebf2f458923fb to your computer and use it in GitHub Desktop.
$list_of_ids = '1,2,3,4,5,6';
if ( cg_validate_int( $list_of_ids ) ) {
echo 'Huzzah! We have valide integers!';
}
/**
* Allows us to pass either an array of or a single intger and validate that they are integers
*
* @param int|string $list_of_ids Pass either a single integer or a comma separated list
*
* @return bool
*/
function cg_validate_int( $list_of_ids ) {
//loop through the split list
foreach (explode( ',', $list_of_ids ) as $id) {
//validate the int by converting back and checking against the original string
//zero will handle properly with this approach
if(strval(intval($id)) !== $id) {
//short circuit if you find a bad value, no need to continue
return false;
}
}
//if you got here, the list is good
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment