PHPKonf Istanbul PHP Conference 2019 - Call for Papers

Arithmetische Operatoren

Erinnern Sie sich noch an die Grundrechenarten aus der Schule? Die arithmetischen Operatoren funktionieren genauso:

Arithmetische Operatoren
Beispiel Name Ergebnis
+$a Identität Umwandlung von $a nach int oder float wie angebracht.
-$a Negation Gegenzahl von $a.
$a + $b Addition Summe von $aa 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.
$a ** $b Potenz $b-te Potenz von $a. (von PHP 5.6 an)

Der Divisionsoperator ("/") gibt einen Fließkommawert zurück, es sei denn beide Operanden sind Ganzzahlen (oder Zeichenketten, die in Ganzzahlen umgewandelt werden), und die Zahlen können glatt geteilt werden; in diesem Fall wird eine Ganzzahl zurückgegeben. Für Ganzzahldivision siehe intdiv().

Operanden des Modulusoperators werden vor der Verarbeitung in Ganzzahlen umgewandelt (indem die Nachkommastellen entfernt werden). Für den Fließkommazahlen-Modulus ist fmod() verfügbar.

Das Ergebnis des Modulusoperators % hat dasselbe Vorzeichen wie der Dividend, d.h. das Ergebnis von $a % $b hat dasselbe Vorzeichen wie $a. Zum Beispiel:


echo (3)."\n";           // gibt 2 aus
echo (% -3)."\n";          // gibt 2 aus
echo (-3)."\n";          // gibt -2 aus
echo (-% -3)."\n";         // gibt -2 aus


Siehe auch im Handbuch das Kapitel über Mathematische Funktionen.

add a note add a note

User Contributed Notes 13 notes

Jonathon Reinhart
12 years ago
A very simple yet maybe not obvious use of the modulus (%) operator is to check if an integer is odd or even.
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.

for ($i = 1; $i <= 10; $i++) {
$i % 2) == 1//odd
{echo "<div class=\"dark\">$i</div>";}
{echo "<div class=\"light\">$i</div>";}
pr dot dot dot dot k at g dot dot dot com
1 year ago
The modulus operator is very poorly suited for such a simple operation as determining if an int is even or odd. On most common systems, modulus performs a division, which is a very slow operation.
A much better way to find if a number is even or odd is to use the bitwise & operator.


$is_odd = $x & 1; //using and
$is_odd = $x % 2; //using modulus
info at sima-pc dot com
14 years ago
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.
1 year ago
To get a positiv result

function modulo(int $a, int $b):?int {
  if ($b == 0) {
    throw new Exception('modulo : second operand must not be zero');
  $b = abs($b);
  // test $b == 1 for performance when $a < 0
  return ($b == 1) ? 0 : (($a < 0) ? modulo($a + $b, $b) : $a % $b);
arjini at gmail dot com
14 years ago
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.

= dir('./');
$i = 0;
false !== ($e = $d->read())){
'<img src="'.$e.'"/>'.chr(10);

For tables just put </tr><tr> in place of the break.
10 years ago
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:
/* tested under PHP 5.2.6-1 with Suhosin-Patch (cli) on both i386 and amd64, Debian lenny/sid */
$a = 2863311530;
$b = 256;
$c = $a % $b;
"$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).
Dominik Buechler
4 years ago
In addition to Jonathan's comment, there is a way simpler way to determine if an integer is even or not:

<? $odd = $i % 2; ?>
<? $even = !($i % 2); ?>

This works because a modulo division by 2 will always return either 0 or the rest 1. Since those are valid boolean values you can just invert them by adding a prefixed ! if wanted.
lmc at trendicy dot com
4 years ago
If you are running a php version older than 5.6, you can calculate $a ** $b by using exp($b*log($a))
5 years ago
The % operator doesn't behave as many people with a maths background would expect, when dealing with negative numbers. For example, -1 mod 8 = 7, but in PHP, -1 % 8 = -1.

The following function has the expected behaviour:

function mod($a, $n) {
    return ($a % $n) + ($a < 0 ? $n : 0);

mod(-1, 8) returns 7 as expected.
peter at icb dot at
1 year ago
If you need the mathematical modulo (always positive) from negative numbers, use this small function:

function modulo($a , $b) { return ($a + $b) % $b; }

// examples:
echo modulo(15, 12);  // 3
echo modulo(-9, 12);  // 3
calmarius at atw dot hu
10 years ago
Be careful when using % with large numbers.

The code:

echo 3333333333 % 3

puts out -1 instead of zero!

(Due to the overflow)
glenn at benge dot co dot nz
14 years ago
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.
php at richardneill dot org
7 years ago
For larger numbers (above PHP_INT_MAX), use fmod() rather than %.
The other operators (+-*/) work correctly with floats and integer overflow, but % uses integer wrap. Eg.

(0xffffffff % 2);
//Prints  int(-1)   which is WRONG

//Prints int(1)   which is the right answer

(The reason this matters is that PHP's float is actually a double, and can accurately represent integers up to 52-bits, even on 32-bit systems)
To Top