Forum Moderators: coopster
$str = (int)$_POST['str'];
... but I'm not sure of the result if it doesn't cast properly (might evaluate to null). Another way, since the form data is always a string, is to detect with a regex:
function isNumber($number)
{
return preg_match('/^[0-9]+$/', $number);
}
// then use it ...
if (isNumber($int) ¦¦ isNumber($str) ... )
{
// do stuff
} else {
// spit out error
}
Regex's consume more resources, but you'd get your desired result. The typecasting I'm not sure about the result if a non whole number is used.
Another method might be to make sure the post data is converted to a true integer by dividing it by one (an old trick, but I think it'll still work):
$str = $_POST['str']/1;
$int = $_POST['int']/1;
if (is_int($str) ¦¦ is_int($str) ... )
{
}
Try some of those and see how you get on.
use if is_numeric and match for a . in the submitted string
use floor to always round down
use round and give them a confirm page "did you really want to use X"
though the first is the best
if (!is_numeric($mynum) ¦¦!(strpos($mynum, ',')===false)) {
echo 'your number format is all messed up';
}
though I haven't had enough coffee yet that is close to right ;)
<?php
$str = 1;
$sta = "3";
$dex = "2";
$agi = "4";if ( is_int_string($str) and is_int_string($sta) and is_int_string($dex) and is_int_string($agi)) {
echo "Integers or integer strings.";
} else {
echo "1 or more non-integers.";
}
function is_int_string($variant) {
return is_int(0 + $variant );
}
?>
This returns "Integers" but if the user enters "4.1" or even '4.0" it returns "non-integers."
You've used typecasting, (which is not just a programming term), which tells the variable you are assigning to expect a certain variable type (in your case an integer). If you try putting a string in there I think it'll end up giving a value of null, but I could be wrong.