From the basics of numeric types in PHP to operators, rounding, bitwise operations, formatting, and conversions, this guide explains everything in an easy-to-understand manner for beginners.
What Numeric Types Can Be Used in PHP? Differences Between Integers and Floating-Point Numbers
PHP mainly handles the following two types of numeric values. Being aware of types can help prevent unexpected errors and accuracy issues.
- Integer (int): Numbers without a decimal point
- Floating-point (float or double): Numbers with a decimal point
Basic Functions for Type Checking and Conversion with Examples
Function | Description | Example |
---|---|---|
gettype($var) | Returns the type of a variable as a string | gettype(100) → "integer" |
is_int($var) | Checks if the value is an integer (bool) | is_int(3.14) → false |
is_float($var) | Checks if the value is a float (bool) | is_float(3.14) → true |
intval($var) | Casts the value to an integer | intval("12 apples") → 12 |
floatval($var) | Casts the value to a float | floatval("3.14xyz") → 3.14 |
<?php
$int = 100; // Integer
$float = 3.14; // Floating-point number
echo gettype($int); // Output: integer
echo gettype($float); // Output: double
?>
List of Arithmetic Operators in PHP and Their Basic Usage
By using arithmetic operators in PHP, you can perform basic calculations such as addition, subtraction, multiplication, division, and modulus.
Operator | Meaning | Example | Result Example |
---|---|---|---|
+ | Addition | $a + $b | Sum of left and right operands |
- | Subtraction | $a - $b | Difference by subtracting right from left |
* | Multiplication | $a * $b | Product of left and right operands |
/ | Division | $a / $b | Quotient of left divided by right |
% | Modulus | $a % $b | Remainder of left divided by right |
** | Exponentiation | $a ** $b | $a raised to the power of $b |
Addition (+
)
Adds two numbers. To concatenate strings, use the .
(dot) operator.
Subtraction (-
)
Subtracts the right operand from the left.
Multiplication (*
)
Multiplies the left and right operands.
Division (/
)
Divides the left operand by the right. The result may automatically become a float
.
Modulus (%
)
Returns the remainder after division. Commonly used for determining odd/even numbers or in loop operations.
Exponentiation (**
)
Available from PHP 5.6. $a ** $b
returns the value of $a raised to the power of $b.
Basic Usage
<?php
$a = 10;
$b = 3;
echo $a + $b; // 13
echo "\n";
echo $a - $b; // 7
echo "\n";
echo $a * $b; // 30
echo "\n";
echo $a / $b; // 3.3333333333333
echo "\n";
echo $a % $b; // 1
echo "\n";
echo $a ** $b; // 10 to the power of 3 = 1000
?>
Basics of Bitwise Operators: How to Use AND, OR, XOR, and Bit Shifts
Bitwise operators perform operations by treating numbers as binary values. Although not frequently used, they can be helpful for efficient flag management and performance optimization.
Operator | Description | Example |
---|---|---|
& | AND | $a & $b |
` | ` | OR |
^ | XOR | $a ^ $b |
~ | NOT | ~$a |
<< | Left Shift | $a << 1 |
>> | Right Shift | $a >> 1 |
<?php
$a = 6; // 110
$b = 3; // 011
echo $a & $b; // 2 (binary: 010)
?>
Rounding Numbers: How to Floor, Ceil, and Round in PHP
PHP provides functions for handling decimal rounding.
<?php
$num = 3.75;
echo floor($num); // 3: Round down
echo ceil($num); // 4: Round up
echo round($num); // 4: Round to nearest
?>
Number Formatting: How to Add Separators and Format Decimals
When displaying numbers, formatting them in a readable way is important. The number_format()
function allows you to neatly output currency or statistical values.
<?php
$price = 1234567.89;
echo number_format($price); // 1,234,568
echo number_format($price, 2); // 1,234,567.89
?>
How to Use Functions to Generate Random Numbers
PHP provides several functions to generate random numbers.
<?php
echo rand(1, 100); // Random integer between 1 and 100
echo mt_rand(1, 1000); // Faster random integer generation
?>
If you need cryptographically secure random numbers, use random_int()
(available from PHP 7).
<?php
echo random_int(1, 10); // Secure random number
?>
Conversion Between Numbers and Strings, and Summary of Number Handling Functions
In PHP, you can convert between numbers and strings, but be careful of unintended type conversions.
1. Type Conversion (Casting / Dedicated Functions)
Method / Function | Description | Sample |
---|---|---|
(int)$var | Casts variable to integer | (int)"123px" → 123 |
(float)$var | Casts variable to float | (float)"3.14abc" → 3.14 |
(string)$var | Casts variable to string | (string)100 → "100" |
intval($var) | Converts variable to integer (same as cast) | intval("12 apples") → 12 |
floatval($var) | Converts variable to float | floatval("2.5e2") → 250.0 |
strval($var) | Converts variable to string | strval(3.14) → "3.14" |
settype($var, $type) | Changes the variable’s type to $type (“int”/”float”/”string”…) | settype($x, "int"); |
<?php
$str = "100px";
$num1 = (int)$str; // 100
$num2 = intval($str); // 100
$flt = (float)"3.14abc"; // 3.14
$s = strval(123.45); // "123.45"
var_dump($num1, $num2, $flt, $s);
?>
2. String Formatting
Function | Description | Sample |
---|---|---|
number_format($num) | Returns string with commas every 3 digits, no decimal places | number_format(1234567) → "1,234,567" |
number_format($num, d) | Rounds to d decimal places and returns as string | number_format(3.14159, 2) → "3.14" |
sprintf() /printf() | Generates/outputs a string with format specifiers | sprintf("%.2f", 2.5) → "2.50" |
<?php
$price = 9876543.21;
echo number_format($price); // 9,876,543
echo "\n";
echo number_format($price, 1); // 9,876,543.2
echo sprintf("Balance is %.2f yen", 1234.5);
// Output: Balance is 1234.50 yen
?>
3. Basic Functions for Numeric Operations
Function | Description | Sample |
---|---|---|
abs($num) | Returns the absolute value | abs(-5) → 5 |
round($num, d) | Rounds to the nearest value (up to d decimal places) | round(3.14159, 3) → 3.142 |
ceil($num) | Rounds up | ceil(2.1) → 3 |
floor($num) | Rounds down | floor(2.9) → 2 |
max($a, $b, …) | Returns the maximum value among the arguments | max(1, 5, 3) → 5 |
min($a, $b, …) | Returns the minimum value among the arguments | min(1, 5, 3) → 1 |
pow($a, $b) | Exponentiation (equivalent to $a ** $b ) | pow(2, 3) → 8 |
sqrt($num) | Square root | sqrt(16) → 4 |
rand($min, $max) | Returns a pseudo-random number within the range | rand(1, 100) → 57 |
<?php
echo abs(-10), "\n"; // 10
echo round(2.71828, 2), "\n"; // 2.72
echo ceil(4.2), "\n"; // 5
echo floor(4.8), "\n"; // 4
echo max(3, 7, 2), "\n"; // 7
echo min(3, 7, 2), "\n"; // 2
echo pow(3, 4), "\n"; // 81
echo sqrt(81), "\n"; // 9
echo rand(1, 10), "\n"; // e.g. 4
?>
List of Commonly Used Numeric Functions
Function | Description |
---|---|
abs() | Returns the absolute value |
round() | Rounds to the nearest value |
floor() | Rounds down |
ceil() | Rounds up |
number_format() | Formats the number for display |
Summary
Numeric operations in PHP are essential in many aspects of web development.
This article has covered everything from basic numeric types to operators, rounding, bitwise operations, formatting, random number generation, and type conversion.
For beginners, we recommend deepening your understanding by writing and experimenting with actual code.