PHP Numbers 🎯

beginner
14 min

PHP Numbers 🎯

Welcome to the PHP Numbers tutorial! In this lesson, we'll dive deep into the world of numbers in PHP, learning about various types, arithmetic operations, and practical examples. Let's get started!

PHP Number Types πŸ“

In PHP, numbers can be of two types:

  1. Integers (whole numbers like 12, -345, or 0)
  2. Floating-point numbers (decimal numbers like 3.14, -0.00005, or 2.718)

Arithmetic Operations πŸ’‘

PHP supports basic arithmetic operations: addition, subtraction, multiplication, division, and modulus (remainder). Let's see how these are done.

Addition πŸ“

php
$a = 5; $b = 3; $sum = $a + $b; echo $sum; // Output: 8

Subtraction πŸ“

php
$a = 10; $b = 4; $subtraction = $a - $b; echo $subtraction; // Output: 6

Multiplication πŸ“

php
$a = 7; $b = 2; $multiplication = $a * $b; echo $multiplication; // Output: 14

Division πŸ“

php
$a = 20; $b = 5; $division = $a / $b; echo $division; // Output: 4

Modulus πŸ“

php
$a = 17; $b = 3; $modulus = $a % $b; echo $modulus; // Output: 2

Advanced PHP Number Topics πŸ’‘

We'll now explore advanced PHP number topics like variables, constants, and the math functions library.

Variables πŸ’‘

Variables in PHP are used to store values that can be changed during runtime. Here's an example:

php
$number = 10; echo $number; // Output: 10 $number = 20; echo $number; // Output: 20

Constants πŸ’‘

Constants are variables that cannot be changed once they're assigned a value. They're defined using the define() function or the const keyword.

php
// Using define() define('PI', 3.14159); echo PI; // Output: 3.14159 // Using const const GRAVITY = 9.81; echo GRAVITY; // Output: 9.81

Math Functions Library πŸ’‘

PHP provides a built-in math functions library to perform complex mathematical operations. Here are a few examples:

php
// Sqrt (square root) $number = 16; $squareRoot = sqrt($number); echo $squareRoot; // Output: 4 // Pow (power) $base = 2; $exponent = 8; $power = pow($base, $exponent); echo $power; // Output: 256 // Round (rounds a number to a specified precision) $number = 3.14159265; $roundedNumber = round($number, 2); echo $roundedNumber; // Output: 3.14

Quiz πŸ“

Quick Quiz
Question 1 of 1

What is the output of the following code snippet?

By now, you've learned the basics and some advanced concepts of PHP numbers. With practice, you'll be able to create impressive PHP applications that involve complex mathematical computations. Happy coding! 🀘