Skip to content

Instantly share code, notes, and snippets.

@EnragedSuccubus
Last active August 29, 2015 14:04
Show Gist options
  • Save EnragedSuccubus/afc5fff15d660f498762 to your computer and use it in GitHub Desktop.
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
$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;
}
@sfrench
Copy link

sfrench commented Jul 31, 2014

Forked and posted a version that short circuits for efficiency on operating over long lists, and handles the zero by doing a reverse conversion

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