PHP Operadores
Autor: Adb | Publicado: 2016-08-23T05:52:00-07:00



Lembra-se da aritmética básica da escola? Estes operadores funcionam exatamente como aqueles.
Operadores Aritméticos
ExemploNomeResultado

-$aNegaçãoOposto de&nbsp;$a.
$a + $bAdiçãoSoma de&nbsp;$a&nbsp;e&nbsp;$b.
$a - $bSubtraçãoDiferença entre&nbsp;$a&nbsp;e&nbsp;$b.
$a * $bMultiplicaçãoProduto de&nbsp;$a&nbsp;e&nbsp;$b.
$a / $bDivisãoQuociente de&nbsp;$a&nbsp;e&nbsp;$b.
$a % $bMóduloResto de&nbsp;$a&nbsp;dividido por&nbsp;$b.
$a ** $bExponencialResultado de&nbsp;$a&nbsp;elevado a&nbsp;$b. Introduzido no PHP 5.6.


O operador de divisão ("/") sempre retorna um valor com ponto flutuante, a não ser que os dois operandos sejam inteiros (ou strings que são convertidas para inteiros) e números inteiramente divisíveis, nesse caso um inteiro é retornado.

Operandos de módulo são convertidos para inteiros (removendo a parte decimal) antes do processamento.

O resultado do operador de módulo&nbsp;%&nbsp;tem o mesmo sinal do dividendo — ou seja, o resultado de&nbsp;$a % $b&nbsp;terá o mesmo sinal de&nbsp;$a. Exemplos:



echo&nbsp;(5&nbsp;%&nbsp;3)."\n";&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;imprime&nbsp;2echo&nbsp;(5&nbsp;%&nbsp;-3)."\n";&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;imprime&nbsp;2echo&nbsp;(-5&nbsp;%&nbsp;3)."\n";&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;imprime&nbsp;-2echo&nbsp;(-5&nbsp;%&nbsp;-3)."\n";&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;imprime&nbsp;-2?&gt;



Veja também a página do manual sobre&nbsp;funções matemáticas.


&nbsp;add a note
User Contributed Notes&nbsp;11 notes





up

down

32

Jonathon Reinhart&nbsp;¶
9 years ago


A very simple yet maybe not obvious use of the modulus (%) operator is to check if an integer is odd or even.&nbsp;&nbsp;if (($a&nbsp;%&nbsp;2) ==&nbsp;1)&nbsp; { echo&nbsp;"$a&nbsp;is odd."&nbsp;;}&nbsp; if (($a&nbsp;%&nbsp;2) ==&nbsp;0)&nbsp; { echo&nbsp;"$a&nbsp;is even."&nbsp;;}?&gt;This is nice when you want to make alternating-color rows on a table, or divs.&nbsp;&nbsp;for ($i&nbsp;=&nbsp;1;&nbsp;$i&nbsp;&lt;=&nbsp;10;&nbsp;$i++) {&nbsp; &nbsp; if(($i&nbsp;%&nbsp;2) ==&nbsp;1)&nbsp;&nbsp;//odd&nbsp; &nbsp; &nbsp;&nbsp;{echo&nbsp;"

$i
"


;}&nbsp; &nbsp; else&nbsp;&nbsp;&nbsp;//even&nbsp; &nbsp; &nbsp;&nbsp;{echo&nbsp;"

$i";}&nbsp;&nbsp; }?&gt;


up

down

12

info at sima-pc dot com&nbsp;¶
12 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.





up

down

10

arjini at gmail dot com&nbsp;¶
11 years ago


When dealing purely with HTML, especially tables, or other things in "grids"&nbsp; 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.&nbsp; &nbsp; $d&nbsp;=&nbsp;dir('./');&nbsp; &nbsp;&nbsp;$i&nbsp;=&nbsp;0;&nbsp; &nbsp; while(false&nbsp;!== ($e&nbsp;=&nbsp;$d-&gt;read())){&nbsp; &nbsp; &nbsp; &nbsp; if(strpos($e,'.gif')){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ++$i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo&nbsp;'.$e.'"/&gt;'.chr(10);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(!($i%5))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo&nbsp;'';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }?&gt;For tables just put 


 in place of the break.



up

down

5

TheWanderer&nbsp;¶
8 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 0.9.6.2 (cli) on both i386 and amd64, Debian lenny/sid */$a&nbsp;=&nbsp;2863311530;$b&nbsp;=&nbsp;256;$c&nbsp;=&nbsp;$a&nbsp;%&nbsp;$b;echo&nbsp;"$c\n";echo (2863311530&nbsp;%&nbsp;256)." \n";&nbsp;/* directly with no variables, just to be sure */?&gt;The code is expected to produce '170' if working correctly (try it in spreadsheet software).





up

down

1

Dominik Buechler&nbsp;¶
1 year ago


In addition to Jonathan's comment, there is a way simpler way to determine if an integer is even or not:orThis 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.





up

down

-1

lmc at trendicy dot com&nbsp;¶
1 year ago


If you are running a php version older than 5.6, you can calculate $a ** $b by using exp($b*log($a))





up

down

-1

Andrew&nbsp;¶
3 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) {&nbsp; &nbsp; return ($a % $n) + ($a &lt; 0 ? $n : 0);}mod(-1, 8) returns 7 as expected.





up

down

-11

calmarius at atw dot hu&nbsp;¶
8 years ago


Be careful when using % with large numbers.The code:&nbsp; &nbsp;&nbsp;echo&nbsp;3333333333&nbsp;%&nbsp;3?&gt;puts out -1 instead of zero!(Due to the overflow)





up

down

-11

pww8 at cornell dot edu&nbsp;¶
11 years ago


It appears floating-point infinity (INF) is not returned from divide by zero (in PHP 5.0.0).&nbsp; 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.





up

down

-10

glenn at benge dot co dot nz&nbsp;¶
11 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.





up

down

-20

php at richardneill dot org&nbsp;¶
5 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.var_dump(0xffffffff&nbsp;%&nbsp;2);&nbsp;//Prints&nbsp; int(-1)&nbsp;&nbsp; which is WRONGvar_dump(intval(fmod(0xffffffff,2)));&nbsp;//Prints int(1)&nbsp;&nbsp; which is the right answer&nbsp;?&gt;&nbsp;(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)