PHP Number
In PHP, numbers can be represented in different formats: integers and floating-point numbers. Here’s a quick overview with examples:
Integers
Integers are whole numbers, positive or negative, without any decimal point.
- Decimal:
123
- Octal (base 8):
075
(equivalent to decimal 61) - Hexadecimal (base 16):
0x1A
(equivalent to decimal 26)
Example:
<?php
$decimal = 123;
$octal = 075; // 61 in decimal
$hexadecimal = 0x1A; // 26 in decimal
echo "Decimal: $decimal\n";
echo "Octal: $octal\n";
echo "Hexadecimal: $hexadecimal\n";
?>
Output:
Decimal: 123
Octal: 61
Hexadecimal: 26
Floating-Point Numbers
Floating-point numbers are numbers with a decimal point. They can represent both very small and very large numbers.
Example:
<?php
$float1 = 3.14;
$float2 = -0.0001;
$float3 = 2.5e3; // 2.5 x 10^3 = 2500
echo "Float1: $float1\n";
echo "Float2: $float2\n";
echo "Float3: $float3\n";
?>
Output:
Float1: 3.14
Float2: -0.0001
Float3: 2500
Type Casting
PHP automatically converts between types when necessary. However, you can explicitly cast types using type casting operators.
Example:
<?php
$integer = 10;
$float = (float)$integer; // Casting integer to float
echo "Integer: $integer\n";
echo "Float after casting: $float\n";
?>
Output:
Integer: 10
Float after casting: 10
Numeric Functions
PHP provides several functions for working with numbers:
abs($number)
: Returns the absolute value.round($number, $precision)
: Rounds the number to a specified precision.ceil($number)
: Rounds up to the nearest integer.floor($number)
: Rounds down to the nearest integer.
Example:
<?php
$number = -3.7;
echo "Absolute value: " . abs($number) . "\n";
echo "Rounded: " . round($number) . "\n";
echo "Ceiling: " . ceil($number) . "\n";
echo "Floor: " . floor($number) . "\n";
?>
Output:
Absolute value: 3.7
Rounded: -4
Ceiling: -3
Floor: -4
These examples cover the basics of working with numbers in PHP. If you have any specific questions or need more advanced details, feel free to ask!
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.