iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Numbers

PHP has two numeric types — int and float. Integer size is platform-dependent (64-bit on every modern system); floats are IEEE-754 binary.

Operators

OperatorReturns
+ - * / %Standard arithmetic.
**Exponentiation.
intdiv($a, $b)Integer division (floor).
++ --Increment / decrement.
PHP
echo 7 / 2;        // 3.5  (always float)
echo intdiv(7, 2); // 3    (int)
echo 7 % 2;        // 1    (modulo)
echo 2 ** 10;      // 1024 (power)

Integers

  • Written in decimal, hex (0xff), octal (0o77), or binary (0b1010).
  • Digit separators: 1_000_000 reads better than 1000000.
  • Overflow promotes to float automatically.

Floats — beware precision

PHP
var_dump(0.1 + 0.2);       // float(0.30000000000000004)
var_dump(0.1 + 0.2 === 0.3); // false — surprising!

For money use integer cents, or bcmath / brick/math:

PHP
echo bcadd('0.1', '0.2', 1);  // 0.3

Useful built-ins

PHP
echo abs(-7);             // 7
echo round(3.567, 2);     // 3.57
echo floor(3.9);          // 3
echo ceil(3.1);           // 4
echo min(3, 1, 2);        // 1
echo max(3, 1, 2);        // 3
echo random_int(1, 6);    // dice roll
Tip: Use random_int() for anything user-facing or security-related. rand() / mt_rand() use a faster but predictable PRNG.

Example

Example
<?php
echo 7 + 2, PHP_EOL;
echo 7 / 2, PHP_EOL;
echo intdiv(7, 2), PHP_EOL;
echo 7 % 2, PHP_EOL;
echo 2 ** 10, PHP_EOL;
Try it Yourself »

Exercise

Cryptographically safe random int.

(1, 6)

Test yourself

Q1. 7 / 2 in PHP returns…
Q2. For money, prefer…
Q3. Cryptographically safe random int is…

Discussion

Loading…