PHP - Integers
In PHP, an integer is a data type that represents a whole number without any fractional or decimal component. Integers can be positive, negative, or zero.
Defining Integers
You can define integers directly by assigning a whole number to a variable.
Example:
php<?php
$positiveInt = 123;
$negativeInt = -456;
$zero = 0;
?>
Integer Range
The range of integers depends on the platform (32-bit or 64-bit). On a 32-bit system, integers can typically range from -2,147,483,648 to 2,147,483,647. On a 64-bit system, the range is much larger, from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
Integer Literals
PHP supports different notations for integer literals:
1. Decimal (Base 10)
The most common form, using digits 0-9.
Example:
php<?php
$decimal = 42;
?>
2. Hexadecimal (Base 16)
Uses digits 0-9 and letters A-F, prefixed by 0x
.
Example:
php<?php
$hexadecimal = 0x2A; // Equivalent to 42 in decimal
?>
3. Octal (Base 8)
Uses digits 0-7, prefixed by 0
.
Example:
php<?php
$octal = 052; // Equivalent to 42 in decimal
?>
4. Binary (Base 2)
Uses digits 0-1, prefixed by 0b
.
Example:
php<?php
$binary = 0b101010; // Equivalent to 42 in decimal
?>
Type Casting
You can explicitly cast a variable to an integer using (int)
or (integer)
.
Example:
php<?php
$float = 3.14;
$int = (int)$float; // $int is 3
?>
Integer Operations
PHP supports standard arithmetic operations with integers:
1. Addition (+
)
Example:
php<?php
$a = 10;
$b = 5;
$sum = $a + $b; // $sum is 15
?>
2. Subtraction (-
)
Example:
php<?php
$a = 10;
$b = 5;
$difference = $a - $b; // $difference is 5
?>
3. Multiplication (*
)
Example:
php<?php
$a = 10;
$b = 5;
$product = $a * $b; // $product is 50
?>
4. Division (/
)
Example:
php<?php
$a = 10;
$b = 5;
$quotient = $a / $b; // $quotient is 2
?>
5. Modulus (%
)
Returns the remainder of the division.
Example:
php<?php
$a = 10;
$b = 3;
$remainder = $a % $b; // $remainder is 1
?>
Integer Functions
PHP provides several built-in functions to work with integers:
1. is_int()
or is_integer()
Checks if a variable is an integer.
Example:
php<?php
$var = 123;
if (is_int($var)) {
echo "This is an integer.";
} else {
echo "This is not an integer.";
}
?>
2. intval()
Returns the integer value of a variable.
Example:
php<?php
$var = "123abc";
$intVal = intval($var); // $intVal is 123
?>
3. abs()
Returns the absolute value of an integer.
Example:
php<?php
$var = -123;
$absVal = abs($var); // $absVal is 123
?>
Integer Overflow
When an integer exceeds the platform's maximum integer value, it will be interpreted as a float.
Example:
php<?php
$largeInt = PHP_INT_MAX + 1;
var_dump($largeInt); // Output: float
?>
Summary:
Integers in PHP are used to represent whole numbers and support various notations such as decimal, hexadecimal, octal, and binary. PHP provides a wide range of operations and functions to work with integers. Understanding how to handle integers and their operations is fundamental for effective programming in PHP.