Forum Moderators: coopster
which function does the following. I am confused with the options
if($n/$s = a whole integer)
{
do something
}
else
{
do something else
}
Cheers
if($n % $s)
<edit>added a link to the manual</edit>
Wait a minute...modulus may only work on integers! At least I'm pretty sure that's how Perl [perldoc.com] handles it, and I'm willing to bet PHP does the same...
[edited by: jatar_k at 9:19 pm (utc) on Oct. 16, 2003]
[edit reason] edit as per coopster [/edit]
<?php
$dividend = 7;
$divisor = 2.4;
print $dividend%$divisor; // prints 1
print fmod($dividend, $divisor); // prints 2.2
?>
Anyway, I would use fmod [us3.php.net] as jatar_k suggested. If it is user-supplied data via a form POST, is_int [us3.php.net] will return false because even though it may be a number that the user keyed, the variable brought in is going to be of type string. Even if it is a string numeric, such as '123', is_int will return false. Don't believe me? Try it:
<html><head><title>is_numeric</title></head><body>
<h1>is_int</h1>
<p>
<code>
<?php
if ($_POST['Submit']) {
$number = $_REQUEST['number'];
if (is_int($number)) {
print '$number is ' . $number . '<br />';
} else {
print '$number is ' . gettype($number) . '<br />';
}
if (is_numeric($number) and fmod($number, 2)) {
print 'fmod($number, 2) is ' . fmod($number, 2) . '<br />';
} else {
print 'fmod($number, 2) is ' . gettype($number) . '<br />';
}
}
?>
<form action="<?php print $_SERVER['PHP_SELF'];?>" method="post">
Number: <input type="text" name="number" />
<input type="submit" name="Submit" value="Submit" />
</form>
</code></p></body></html>
By the way, it is important to check that the value the user is supplying you actually is numeric [us3.php.net] before using it in fmod, otherwise, if a text string like 'abc' is POSTed, your code is going to choke and you are going to get a warning message similar to:
Warning: fmod() expects parameter 1 to be double, string given in /your/path/your_code.php on line 21.
Regards,
coopster