Reputation: 3
To start, I'm still a noob with php, and much of what I've learned is from problems being solved across this site that I have also had myself.
I've found the answers here for all of my original questions, but when I put them all together I can't get get the code to work.
I have a basic form that is posting to itself using PHP_SELF. I want all input from the $_POST array to be checked to make sure that it is (1) a positive integer, (2) a whole number, and (3) does not include a decimal.
if( !empty($_POST ) ) {
foreach( $_POST as $key => $amount ) {
if( !is_int($amount) || $amount < 0 || is_float(amount) ) {
die( 'All data must be positive integers.' );
}
}
}
No matter what I type into any of the input fields it always returns the "die" error.
Upvotes: 0
Views: 496
Reputation: 97672
$amount
is a string so is_int
will always fail, try filter_var
instead
if( !empty($_POST ) ) {
$options = array(
'options' => array(
'min_range' => 0
)
);
foreach( $_POST as $key => $amount ) {
if( filter_var($amount, FILTER_VALIDATE_INT, $options) === false ) {
die( 'All data must be positive integers.' );
}
}
}
Upvotes: 3
Reputation: 350
Try this.
if(!empty($_POST)) {
foreach($_POST as $key => $amount) {
if(!(is_int($amount) && $amount >= 0)) {
die( 'All data must be positive integers.' );
}
}
}
Upvotes: 0
Reputation: 167182
Typo in your code. Replace is_float(amount)
with is_float($amount)
.
Upvotes: 0