©
本文档使用 PHP中文网手册 发布
<?php
echo 6 % 3 ;
?>
Function name: (null)
Compiled variables: none
line | # | op | fetch | ext | return | operands |
---|---|---|---|---|---|---|
6 | 0 | MOD | ~0 | 6,3 | ||
1 | ECHO | ~0 | ||||
7 | 2 | RETURN | 1 |
[#1] shripatel at gmail dot com [2015-11-27 05:18:29]
I came across strange mod operation results can anyone explain the behavior
Sorry, if breaking any forum rules.
<?php
$amount=19.90;
$mul=0.10;
$ztmpamt=$amount*100;
$zbidmul=$mul*100;
echo "amount:".$ztmpamt." mul:".$zbidmul;
echo "<br>";
$zcheckmultiple= $ztmpamt % $zbidmul;
echo "Why this is not zero:".$zcheckmultiple;
echo "<br>";
echo "amt:".$ztmpamt.":mul:".$zbidmul;
echo "<br>";
$result= 1990 % 10;
echo "This is zero:".$result;
echo "<br>";
?>
[#2] martynas dot stropa at gmail dot com [2014-10-28 16:45:31]
A function to handle integers of any length, including negatives. Returns remainder but also calculates division in the process (could be useful in some cases).
<?php
function remainder($dividend, $divisor) {
if ($dividend == 0 || $divisor == 0) return 0;
$dividend .= '';
$remainder = 0;
$division = '';
// negative case
while ($dividend < 0) {
$dividend += $divisor;
if ($dividend >= 0) return $dividend;
}
// positive case
while (($remainder.$dividend)*1 > $divisor) {
// get remainder big enough to divide
while ($remainder*1 < $divisor) {
$remainder .= $dividend[0];
$remainder *= 1;
$dividend = substr($dividend, 1);
}
// get highest multiplicator for remainder
$mult = floor($remainder / $divisor);
// add multiplicator to division
$division .= $mult.'';
// subtract from remainder
$remainder -= $mult*$divisor;
}
// add remaining zeros if any, to division
if (strlen($dividend) > 0 && $dividend*1 == 0) {
$division .= $dividend;
}
return $remainder;
}
[#3] doug at unlikelysource dot com [2014-10-05 23:30:07]
To determine odd or even it's faster and more efficient to use the bitwise & operator:
$a = 3;
if ($a & 1) {
echo 'odd';
} else {
echo 'even';
}
// returns 'odd'
[#4] napora dot adam at gmail dot com [2012-05-25 16:22:09]
Might be helpful:
I had to create and "INSERT INTO" on every 50th row:
<?php
$lineBreak = 50;
$tableName = 'user';
$tableFields = 'id, name, password';
?>
in the loop:
<?php
if ($counter === 0 || $counter % $lineBreak === 0) {
echo "INSERT INTO $tableName ($tableFields) VALUES (";
} else {
echo ' (';
}
// add values comma-delimited
if ($counter === 0 || $counter % $lineBreak === 0) {
$insertStmt .= ');';
} else {
$insertStmt .= '),';
}
?>
(in my case I had to check if $no % $o === 0)
[#5] shaunny at hotmail dot com [2010-01-08 06:35:42]
A simple check to see if a number is divisible by another number,
i.e. if a number is even.
<?php
if ($counter % 2) {
echo "This number is not even.";
} else {
echo "This number is even.";
}
?>