-
-
Save sfrench/f3efb25ebf2f458923fb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $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