Lembra-se da aritmética básica da escola? Estes operadores funcionam exatamente como aqueles.
| Exemplo | Nome | Resultado |
|---|---|---|
| -$a | Negação | Oposto de $a. |
| $a + $b | Adição | Soma de $a e $b. |
| $a - $b | Subtração | Diferença entre $a e $b. |
| $a * $b | Multiplicação | Produto de $a e $b. |
| $a / $b | Divisão | Quociente de $a e $b. |
| $a % $b | Módulo | Resto de $a dividido por $b. |
| $a ** $b | Exponencial | Resultado de $a elevado a $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 % tem o mesmo sinal do dividendo — ou seja, o resultado de $a % $b terá o mesmo sinal de $a. Exemplos:
echo (5 % 3)."\n"; // imprime 2echo (5 % -3)."\n"; // imprime 2echo (-5 % 3)."\n"; // imprime -2echo (-5 % -3)."\n"; // imprime -2
?>
Veja também a página do manual sobre funções matemáticas.
User Contributed Notes 11 notes
32
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.
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++) {
if(($i % 2) == 1) //odd
{echo "
$ielse //even
{echo "
}?>
12
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.
10
11 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.
$d = dir('./');
$i = 0;
while(false !== ($e = $d->read())){
if(strpos($e,'.gif')){
++$i;
echo '
.$e.'"/>'.chr(10);
if(!($i%5))
echo '
';
}
}?>
For tables just put
5
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 = 2863311530;$b = 256;$c = $a % $b;
echo "$c
\n";
echo (2863311530 % 256)."
\n"; /* directly with no variables, just to be sure */?>
The code is expected to produce '170' if working correctly (try it in spreadsheet software).
1
1 year ago
In addition to Jonathan's comment, there is a way simpler way to determine if an integer is even or not:
or
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.
-1
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))
-1
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) {
return ($a % $n) + ($a < 0 ? $n : 0);
}
mod(-1, 8) returns 7 as expected.
-11
8 years ago
Be careful when using % with large numbers.
The code:
echo 3333333333 % 3
?>
puts out -1 instead of zero!
(Due to the overflow)
-11
11 years ago
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.
-10
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.
-20
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 % 2); //Prints int(-1) which is WRONG
var_dump(intval(fmod(0xffffffff,2))); //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)
05:52
Adb
Posted in:






0 comentários :
Postar um comentário