Last active
August 29, 2015 14:04
-
-
Save EnragedSuccubus/afc5fff15d660f498762 to your computer and use it in GitHub Desktop.
Validate a string of numbers, even if they are in a list separated by commas
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 ) { | |
// Separate the list and convert the string to an integer | |
$ids = array_map( 'intval', explode( ',', $list_of_ids ) ); | |
// Init array | |
$results = array(); | |
// Loop through each and set a string of true or false | |
foreach ( $ids as $id ) { | |
// If a value was passed that couldn't be converted to an integer, it will result in 0. | |
// If that is the case, validation failed, set false as the value then. | |
// Other wise, we have a valide integer | |
$results[] = ( $id !== 0 ) ? 'true' : 'false'; | |
} | |
// Check if any of the values in our array failed validation | |
if ( in_array( 'false', $results ) ) { | |
return false; | |
} | |
// If everything checked out, then we are good. | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Forked and posted a version that short circuits for efficiency on operating over long lists, and handles the zero by doing a reverse conversion