Erinnern Sie sich noch an die Grundrechenarten aus der Schule? Die arithmetischen Operatoren funktionieren genauso:
Beispiel | Name | Ergebnis |
---|---|---|
$a + $b | Addition | Summe von $a und $b. |
$a - $b | Subtraktion | Differenz von $a und $b. |
$a * $b | Multiplikation | Produkt von $a und $b. |
$a / $b | Division | Quotient von $a und $b. |
$a % $b | Modulus | Rest von $a geteilt durch $b. |
Der Divisions-Operator ("/") gibt immer eine Fließkommazahl zurück, sogar wenn die zwei Operanden Ganzzahlen sind (oder Zeichenketten, die nach Ganzzahlen umgewandelt wurden).
Siehe auch im Handbuch das Kapitel über Mathematische Funktionen.
Note on the modulus operators returning negative values for great numbers... For instance:
<?PHP
$a = pow(2, 31); // You expect it to be 2147483648 but under the surface it's actually -2147483648 because the variable is signed.
$a = 50856937683; // You expect it to be 50856937683 but something odd is going on here where you are breaking the 32 bit storage and it converts to either -682669869 or -1116408691
?>
I don't have the time to actually check which of the two negatives it converts to but that is why it returns a negative value either way.
I notice a trouble with the modulus operator, when trying to work with great values:
<?php
function modulo($val, $div) {
$r = $val - (floor($val/$div)*$div);
return $r;
}
$values = array(375389654, 50856937683);
$divs = array(2, 16, 62);
foreach ($values as $v) {
foreach ($divs as $d) {
echo $v, '%', $d, ' gives ', modulo($v, $d), ' but get ', ($v%$d), '<br />';
}
}
?>
And output :
<?php
/*
375389654%2 gives 0 but get 0
375389654%16 gives 6 but get 6
375389654%62 gives 52 but get 52
50856937683%2 gives 1 but get -1
50856937683%16 gives 3 but get -13
50856937683%62 gives 27 but get -21
*/
?>
Here are three functions dealing with the prime factorization of integers. The first function completely factorizes a number. The second one returns distinct prime factors. The third one returns all its factors.
<?php
function factorize($num) {
// Returns a sorted array of the prime factorization of $num
// Caches prior results. Returns empty array for |$num|<2
// eg. factorize(360) => [5, 3, 3, 2, 2, 2]
static $aFactors = array();
if (2>$num=abs($num)) return array(); // negatives, 1, 0
if ($aFactors[$key = "x$num"]) { // handles doubles
// Been there, done that
if (($factor=$aFactors[$key])==$num) return array($num);
return array_merge(factorize($num/$factor),array($factor)); }
// Find a smallest factor
for ($sqrt = sqrt($num),$factor=2;$factor<=$sqrt;++$factor)
if (floor($num/$factor)==$num/$factor)
return array_merge(factorize($num/$factor),
array($aFactors[$key] = $factor));
return (array($aFactors[$key] = $num)); } // $num is prime
function primeFactors($num) {
// Returns an array of each distinct prime factor of $num
// eg. primeFactors(360) => [5, 3, 2]
return array_keys(array_flip(factorize($num))); }
function allFactors($num) {
// Returns an (unsorted) array of each factor of $num
// eg. allFactors(30) => [1, 5, 3, 15, 2, 10, 6, 30]
// eg. allFactors(64) => [1, 2, 4, 8, 16, 32, 64]
$aFacts = array(1 => 1);
foreach (factorize($num) as $factor)
foreach ($aFacts as $fact => $whatever)
$aFacts[$fact * $factor] = 1;
return array_keys($aFacts); }
?>
Although some would know this, I had to try in order to understand. Modulus and multiplication operators are not associative; they will execute from left to right.
<?php
$a = 23;
$b = 5;
$c = 2;
$d = $a % $b * $c; // <=> (23%5) * 2 = 3 * 2 = 6
$d2 = $c * $a % $b; // <=> (2*23) % 5 = 46 % 5 = 1
var_dump($d);
var_dump($d2);
?>
The rules for converting from string to number are in the manual.
It is not true that 'all strings will be converted to 0' yet it certainly is true that some of them will be.
"1" will be treated as 1 in an arithmetic expression, for example.
It should be noted that every string will be converted to 0.
<?php
/* tested under PHP 5.2.3-1ubuntu6 (cli) (built: Oct 4 2007 23:35:54) */
echo "foo" * "bar";
echo "foo" / "bar";
?>
Results:
0
Warning: Division by zero in /tmp/test.php on line 3
It is worth noticing that when working with large numbers, most noticably using the modulo operator, the results depend on your CPU architecture. Therefore, running a decent 64-bit machine will be to your advantage in case you have to perform complex mathematical operations. Here is some example code - you can compare its output on x86 and x86_64 machines:
<?php
/* tested under PHP 5.2.6-1 with Suhosin-Patch 0.9.6.2 (cli) on both i386 and amd64, Debian lenny/sid */
$a = 2863311530;
$b = 256;
$c = $a % $b;
echo "$c <br />\n";
echo (2863311530 % 256)." <br />\n"; /* directly with no variables, just to be sure */
?>
The code is expected to produce '170' if working correctly (try it in spreadsheet software).
Be careful when using % with large numbers.
The code:
<?php
echo 3333333333 % 3
?>
puts out -1 instead of zero!
(Due to the overflow)
Here's a neat little trick to use ASCII escape codes to show processing in a CLI script.
#!/usr/bin/php -q
<?php
//http://www.cs.csubak.edu/Tables_Charts/VT100_Escape_Codes.html
define('ESC', 27);
printf( "%c[2J", ESC ); //clear screen
//note how the '-' is at [1], not [0]
$cursorArray = array('/','-','\\','|','/','-','\\','|');
echo "Processing: ";
printf( "%c7", ESC ); //save cursor position
for ($count = 1; $count <= 30; $count++)
{
//note that $i is all self contained.
printf("%c8(".$cursorArray[ (($i++ > 7) ? ($i = 1) : ($i % 8)) ].") %02d", ESC, $count); //restore cursor position and print
sleep(1);
}
echo "\nDone.\n";
?>
In reply to TChan:
If the documentation doesn't match the behavior of the language, then this is a bug which needs to be reported and and dealt with by "them" by either fixing the language to behave as the documentation states, or change the documentation to reflect the exceptions and in which version(s) they exist.
Given that we're probably both right for at least some version of PHP ... which doesn't help with people sharing PHP code all over the place :-)
To the comment from nicholas_rainard: Your function is much more efficient, but should probably be combined with the first two lines from the function prior to yours:
function int_divide($x, $y) {
if ($x == 0) return 0;
if ($y == 0) return FALSE;
return ($x - ($x % $y)) / $y;
}
Permits for zero in either argument. Also, this always returns the floor of the division. Probably seems obvious to most, but it didn't to me at first. Maybe a rounding function would look like:
function up_or_dn($x, $y) {
if ($x == 0) return 0;
if ($y == 0) return FALSE;
return ($x % $y >= $y / 2) ?
(($x - ($x % $y)) / $y) + 1 : ($x - ($x % $y)) / $y;
}
Adds 1 if the mod result is more than half $y (which if my math is right means the float result is .5+, so round up).
Simplest example: $x = 3, $y = 2.
Here is another very simple and extremely fast integer division function, but it works only if the arguments are integers and nothing else. So use it only if you are sure of what you are doing.
function int_int_divide($x, $y) {
return ($x - ($x % $y)) / $y;
}
This one is much, much faster than the preceding ones.
gilthansREMOVEME at gmail dot com proposed a nice integer division function, but its speed greatly depends on the size difference between the two provided numbers. If the first number is very big and the second one is very small, this function will take a (relative) long time to resolve (because of the loop).
Here is another integer division function, wich always takes the same time to resolve, what ever the provided numbers are. In most cases, it will be faster, but if the numbers are close, the other one will be twice as fast. It's up to you to choose one of these functions, depending on the expected input numbers...
function int_divide($x, $y) {
if ($x == 0) return 0;
if ($y == 0) return FALSE;
$result = $x/$y;
$pos = strpos($result, '.');
if (!$pos) {
return $result;
} else {
return (int) substr($result, 0, $pos);
}
}
"It *explicitly* says in the documentation that the division operator *always* returns a float value *regardless* of the types of the operands."
Documentation is not always right. See http://uk.php.net/manual/en/language.operators.arithmetic.php#49371
"Actually I think you meant *smaller*, not larger... the reason floor($a/$b) isn't absolutely equatable with the integer division of $a and $b is explained mainly at http://us3.php.net/float . By the look of things, any number with a loss of precision will be truncated instead of rounded. This would at least make sense in the big picture since truncation is more consistant than rounding."
No. The people who wrote IEEE 754 made the default rounding mode round-to-nearest, because it tends to give a more accurate result. To illustrate, if the true value of a/b is (say) 3.9999999999999999999, this will be rounded up to 4. Then, floor(4) = 4, whereas the true value is 3.
That said, it depends on (at least) the particular version of PHP you're running. PHP doesn't guarantee anything - it can use whatever approximate floating point implementation it likes.
following from jonathon's and sean's notes, imho booleans are simpler for alternating rows
<ul>
<?php
$alt=true;
for($i=0;$i<count($items);$i++)
{
echo '<li'.($alt?' class="alternate"':'').'>'.$items[$i].'</li>';
$alt=!$alt;
}
?>
</ul>
1) About integer division: here's a function that neatly solves this. It is somewhat slower than normal division, but is failsafe.
<?php
function integer_divide($x, $y){
//Returns the integer division of $x/$y.
$t = 1;
if($y == 0 || $x == 0)
return 0;
if($x < 0 XOR $y < 0) //Mistaken the XOR in the last instance...
$t = -1;
$x = abs($x);
$y = abs($y);
$ret = 0;
while(($ret+1)*$y <= $x)
$ret++;
return $t*$ret;
}
?>
2) adam.pippin noted about number factoration, however the function returns alot of sequences in text form. This one returns an Array with all the factored numbers of a number. For example, factor(50) would return Array(2, 5, 5).
<?php
function factor($n){
$ret = Array();
$i = 2;
$m = $n/2;
while($i <= $m){
if(!($n%$i))
$ret = array_merge($ret, factor($i), factor($n/$i));
if($i%2)
$i+=2; //$i is impair
else
$i++;
//Ideally, you'd only run through prime numbers, but there is no way to tell what is the next prime number; we can be sure, however, that the pair ones aren't prime.
$m = $n/$i; //If $n isn't divisible by $i, it be assumed it isn't divisible by any number bigger than $n/$i, and if it is divisible by $i, $n/$i is already put in. The derivation for this isn't too complex. This drastically reduces the number of numbers we have to go through during the factoration.
}
if(empty($ret))
return Array($n);
return $ret;
}
?>
This has only been tested for integers, factoration for floats should include some way to identify the divisor.
Hope this saves someone some headaches.
Jonathon Reinhart's neat little function to find out if a value is odd or even doesn't work for floats (this might possibly arithmetically correct but causes the following problem) eg
<?php
12.23 % 2 = 0 not 1
?>
So if you need to find out if the fraction part of a float is odd or even try:
<?php
if (($a /2) != (floor($a /2))){
echo "$a is odd." ;
}
if (($a /2) == (floor($a /2))){
echo "$a is even." ;
}
?>
An easier way of doing alternating row colors is just setting the first row color outside of your loop, calling your loop, and then calling the class or hex code into a single spot, rather than re-creating the entire div both times.
Something like this:
<?php
$class = "odd";
for ($i = 1; $i <= 10; $i++) {
echo "<div class=\"".$class."\">".$i."</div>";
if ($class == "odd") { $class = "even"; } else { $class = "odd"; }
}
?>
A very simple yet maybe not obvious use of the modulus (%) operator is to check if an integer is odd or even.
<?php
if (($a % 2) == 1)
{ echo "$a is odd." ;}
if (($a % 2) == 0)
{ echo "$a is even." ;}
?>
This is nice when you want to make alternating-color rows on a table, or divs.
<?php
for ($i = 1; $i <= 10; $i++) {
if(($i % 2) == 1) //odd
{echo "<div class=\"dark\">$i</div>";}
else //even
{echo "<div class=\"light\">$i</div>";}
}
?>
Quote from TChan's post:
"...But if you're dealing with ints anyway, (a-a%b)/b has no function calls and returns an int, while floor() always returns a float."
It *explicitly* says in the documentation that the division operator *always* returns a float value *regardless* of the types of the operands. While you may get the "integer part" of the number that way you will technically not get an integer. PHP may not be too strongly typed for the most part, but it's important to make the distinction.
"... if the 'fractional part' of $a/$b is close to 1, then it can round up, and floor($a/$b) will be larger than it should be."
Actually I think you meant *smaller*, not larger... the reason floor($a/$b) isn't absolutely equatable with the integer division of $a and $b is explained mainly at http://us3.php.net/float . By the look of things, any number with a loss of precision will be truncated instead of rounded. This would at least make sense in the big picture since truncation is more consistant than rounding.
Please note that floor($a/$b) is not the same as integer division. if the 'fractional part' of $a/$b is close to 1, then it can round up, and floor($a/$b) will be larger than it should be. The example is a bit contrived though (and printf doesn't print enough digits).
<?php printf("%f\n",$a = 9007199254740991); // 9007199254740991.000000
printf("%f\n", $b = $a * 3.0); //27021597764222970.000000, the actual value stored ends in 2 while the true value ends in 3
printf("%f\n", $b/$a - 3.0); //0.000000
printf("%f\n", $b - 2*$a - $a); //-1.000000
printf("%f\n",fmod($b,$a)); //9007199254740990.000000 fmod agrees too
?>
Admittedly it's a bit 'specially-crafted', but it just goes to show. I believe it does work for integers that can be exactly represented in FP. But if you're dealing with ints anyway, (a-a%b)/b has no function calls and returns an int, while floor() always returns a float.
# There are several natural ways to define the mod operator for integers.
# Requirement: If mod(k, m) = r, then k and r differ by a multiple of m.
# For m=7, think days-of-the-week. Both mod(13, 7) = 6 and mod(13, 7) = -1
# satisfy the requirement. Six days from today, or one day ago, are the same DOW.
# There are several natural ways to define the mod operator for integers.
# Requirement: If mod(k, m) = r, then k and r differ by a multiple of m.
# For m=7, think days-of-the-week. Both mod(13, 7) = 6 and mod(13, 7) = -1
# satisfy the requirement. Six days from today, or one day ago, are the same DOW.
# Here are four mod operators:
# 1. mod_php.
# Same as the built-in PHP function, so mod_php($k,$m) == ($k % $m).
# A negative value might jolt a programmer using it for array index.
function mod_php($k, $m) {return $k % $m; }
# 2. Standard math definition.
# Nice. But, if for some reason m is negative, be prepared for negative values.
function mod_math($k, $m) { return ($k - $m * floor($k/$m)); }
# 3. Smallest absolute value.
# Sometimes convenient for large integers, making good use of the sign-bit.
# Also, for mere humans, "-2 months from May", might be easier than "10 months from May".
function mod_min($k, $m) {
$r = mod_pos($k, $m);
if($r > abs($m)/2) $r -= abs($m);
return $r;
}
# 4. Smallest non-negative value.
# Maybe closest to the concept that mod is the remainder when dividing $k by $m.
function mod_pos($k, $m) { return ($k - abs($m) * floor($k/abs($m))); }
# This table compares the four functions.
k m mod_php mod_math mod_min mod_pos
18 7 4 4 -3 4
17 7 3 3 3 3
16 7 2 2 2 2
-16 7 -2 5 -2 5
-17 7 -3 4 -3 4
-18 7 -4 3 3 3
18 -7 4 -3 -3 4
17 -7 3 -4 3 3
16 -7 2 -5 2 2
-16 -7 -2 -2 -2 5
-17 -7 -3 -3 -3 4
-18 -7 -4 -4 3 3
An implementation of the classical modulus operator (as in mathematics or Java). An alternative to the one given below, which was more elegant. This implementation maybe more efficient?
// Computes...
// Mathematics: $a (mod $b)
// Java: $a % $b
function modulus( $a, $b )
{
if( $a < 0 )
{
return $b - ( abs( $a ) % $b );
}
else
{
return $a % $b;
}
}
[ops ... wrong example :D]
just a note about module, it works only with integers.
<?php
$a = pow(2, 31);
$b = ($a / 2) - 1;
echo implode('<br />', array(
$a + $b, // OK => 3221225472
$a - $b, // OK => 1073741825
$a * $b, // OK => 2.3058430070662E+018
$a / $b, // OK => 2.0000000018626
$a % $b // WTF ? => -2
));
?>
maybe bc_mod with a string cast should be a solution
bc_mod((string)pow(2,31), (pow(2,31)/2)-1)
Note that constructs which evaluate to 0 (such as empty strings, false, or an explicit NULL) will be treated as 0 in a arithmetic operation. Therefore:
<?php
echo 5*"", '<br>';
echo 5+false, '<br>';
echo 5/NULL, '<br>';
?>
Will produce:
0
5
Warning: Division by zero
It appears floating-point infinity (INF) is not returned from divide by zero (in PHP 5.0.0). Instead a warning is given and Boolean FALSE is returned.
I searched the various manuals and did not find relevant explanation, so am adding this.
This is a really simple observation.
There is no integer division operator. But if you need to divide by a power of 2, you can use the right-shift operator instead. 257/32 gives 8.03125, but 257>>5 gives 8.
Most of the mail services/bulletin boards display the time when the message was posted or the mail was received in the form - 3 days ago, 15 mins ago etc.
Here is a nifty little PHP function which does the same by basically combining the usage of "/" and "%" operators.
You need to pass the unix timestamp of the time when the message was posted to the function.
function intervalCalc($postedtime)
{
$now = time();
$interval_secs = $now - $postedtime;
if ($interval_secs > 86400)
{
$interval = (($interval_secs - ($interval_secs%86400))/86400);
$interval.= " days ago";
}
elseif ($interval_secs > 3600)
{
$interval = ($interval_secs - ($interval_secs%3600)/3600);
$interval.= " hours ago";
}
elseif ($interval_secs > 60)
{
$interval = ($interval_secs - ($interval_secs%60)/60);
$interval.= " minutes ago";
}
return $interval;
}
I just had to make a comment about gilthans' use of the bitwise xor operator (^)... I'm guessing from the line if(($x < 0 ^ $y < 0) && $x != 0) that he wants to verify that only x or only y is less than 0 AND x != 0... Bitwise operators should not be used for truth values like this, that's what xor is for.
A note about the documentation on this page that I found while teaching a PHP class:
The above statment: "The division operator ("/") returns a float value anytime, even if the two operands are integers (or strings that get converted to integers)." is NOT TRUE.
Take the following:
<?php
$a=5;
$b=10;
$c=$b/$a;
$d=10/5;
var_dump($c);
var_dump($d);
var_dump($b/$a);
var_dump(10/5);
?>
All 4 instances will print "int(2)"
Therefore, the division operator "/" returns an integer value if the numbers are evenly divisible AND they are both integers (or strings that have been converted to integer values).
If you need "div" function like in pascal ( 123 div 10 == 12) you can try this:
$number "div" 10 = ($number-($number % 10)) / 10;
If the second operand of modulus is of a precision type, modulus will return a boolean instead of a numeric type.
Me and a few friends were talking about how math works in coding languages, and after a while of discussion, we started wondering how does the sqrt() function works, and how does the division work, using only addition, substraction and multiplication (because that could be easily done using only addition).
I have best knowledge in PHP, so I had my shot at division, and a while of testing proved that my code works. I'm posting this here for the curious, even though the normal PHP division works 7 times faster, so I think there is some way of making my code more efficient.
divide($x, $y, $a, 0) is similar to number_format($x/$y, $a);, and divide($x, $y, $a, 1) is similar to Array(floor($x/$y), $x%$y).
<?php
function divide($x, $y, $a=6, $z=false){
// returns $x/$y
$t = '';
if($y == 0)
return 0;
if(($x < 0 ^ $y < 0) && $x != 0)
$t = '-';
$x = abs($x);
$y = abs($y);
$in = 0;
while(($in+1)*$y <= $x)
$in++;
$r = $x-($in*$y);
if($z)
return Array($in, $r);
$d = '';
$c = 0;
while($r != 0 && $c < $a){
list($u, $r) = divide($r*10, $y, $a, 1);
$c++;
if($c >= $a){
$b = divide($r*10, $y, $a, 1);
$u += ($b[0] > 4) ? 1 : 0;
}
$d .= $u;
}
return intval($t.$in.(($d != '') ? ".".$d : ""));
}
?>
To factor a number:
<?php
function factornumber($number)
{
for ($i=1; $i<=($number/2); $i++)
{
if ($number % $i == 0)
{
echo "$i * ".($number/$i)." = $number\n";
}
}
}
factornumber(50);
?>
That script outputs:
1 * 50 = 50
2 * 25 = 50
5 * 10 = 50
10 * 5 = 50
25 * 2 = 50
As you may notice, it makes no attempts at removing duplicates (eg: 5*10 and 10*5), although it would be trivial to make it do so.
a real simple method to reset an integer to a the next lowest multiple of a divisor
$startSeq = $startSeq - ($startSeq % $entriesPerPage);
if $startSeq was already a multiple, then " $startSeq % $entriesPerPage " will return 0 and $startSeq will not change.
When dealing purely with HTML, especially tables, or other things in "grids" the modulous operator is really useful for splitting up the data with a seperator.
This snippet reads any gif files from the directory the script is in, prints them out and puts in a break every 5th image.
<?php
$d = dir('./');
$i = 0;
while(false !== ($e = $d->read())){
if(strpos($e,'.gif')){
++$i;
echo '<img src="'.$e.'"/>'.chr(10);
if(!($i%5))
echo '<br/>';
}
}
?>
For tables just put </tr><tr> in place of the break.
The function below is not a replacement for http://php.net/fmod Rather, it is the classic (mathematician's) modulo where the resultant value is always non-negative, in the range [0,$base). For example, mod(-9,7) => 5. When both arguments are integers, you get the classic notion of the % operator.
function mod($num, $base) {
return ($num - $base*floor($num/$base)); }
Csaba Gabor
Note that operator % (modulus) works just with integers (between -214748348 and 2147483647) while fmod() works with short and large numbers.
Modulus with non integer numbers will give unpredictable results.
For the mathematicians among us:
The mod operator % works a bit differently than in mathematics (e.g. in group theory), in that negative remainders aren't represented by their positive equivalence classes, as is common in mathematics.
An example:
-1%7 returns -1, instead of 6.
it depends a bit on how you interpret 'remainder of a division', i.e. if you want the remainder to be always positive.
Exponentiation doesn't use ^ or ** as you might be used to with other languages. To calculate "z equals y to the x" use:
$z = pow(y,x)
Also, when automatically converting floats to integers, PHP truncates them rather than rounding. So in the previous note, 2.4 gets truncated to 2 before the modulus operator is applied.
There isn't much detail in the PHP Manual regarding the PHP modulus operator (%). It seems as though the PHP modulus operator (%) works on integer operands. If PHP operates like Perl, then the modulus operator (%) converts its operands to integers before finding the remainder according to integer division. Testing seems to prove the theory:
<?php
$dividend = 7;
$divisor = 2.4;
print $dividend%$divisor; // prints 1
print fmod($dividend, $divisor); // prints 2.2
?>