$post is used to simulate $_POST, and I found that $_POST['int'] is a string.
How can I tell whether $post['int'] is an integer?
The following indicates that it is not an integer.
<?php
$post=array('int'=>(string)123);
var_dump($post);
echo(is_int($post['int'])?'int':'not int');
?>
EDIT. Per the documentation (http://php.net/manual/en/function.is-int.php), is_int — Find whether the type of a variable is integer, so obviously it does exactly what it is suppose to do. Still need to tell whether the string is an integer...
If you really want to know if the value is an integer you can use filter_input(). Important: you can not test this with a fake $_POST var, you really have to post the value or use INPUT_GET for testing and append ?int=344 to your URL
// INPUT_POST => define that the input is the $_POST var
// 'int' => the index of $_POST you want to validate i.e. $_POST['int']
// FILTER_VALIDATE_INT => is it a valid integer
filter_input( INPUT_POST, 'int', FILTER_VALIDATE_INT );
Working example:
<form action="" method="post">
<input type="text" name="int" />
<input type="submit" />
</form>
<?php
if( isset( $_POST["int"] ) ) {
echo( filter_input( INPUT_POST, 'int', FILTER_VALIDATE_INT ) ) ? 'int' : 'not int';
}
Update: Due to the comment of @user1032531's answer
I would have thought a baked-in solution would have been available
There is a built in function called filter_var(), that function does the same like the above example, but it doesn't need a POST or GET, you can simply pass a value or variable to it:
var_dump( filter_var ( 5, FILTER_VALIDATE_INT ) );// 5
var_dump( filter_var ( 5.5, FILTER_VALIDATE_INT ) );// false
var_dump( filter_var ( "5", FILTER_VALIDATE_INT ) );// 5
var_dump( filter_var ( "5a", FILTER_VALIDATE_INT ) );// false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With