</>
Skip to content
PHP lessons (12/49)

PHP — Math

Basic math

<?php
echo abs(-5);          // 5
echo round(3.14159, 2); // 3.14
echo ceil(3.1);        // 4
echo floor(3.9);       // 3
echo sqrt(16);         // 4
echo pow(2, 10);       // 1024
echo max(1, 2, 3);     // 3
echo min(1, 2, 3);     // 1
?>

Random numbers

<?php
echo rand(1, 100);        // Random int 1-100
echo random_int(1, 100);  // Cryptographic random
echo mt_rand(1, 100);     // Mersenne Twister
?>

Trigonometry

<?php
echo sin(0);    // 0
echo cos(0);    // 1
echo tan(0);    // 0
echo M_PI;      // 3.14159265358979
echo rad2deg(M_PI); // 180
echo deg2rad(180);  // 3.14159...
?>

Logarithmic

<?php
echo log(100);     // 4.605...
echo log10(100);   // 2
echo log(M_E);     // 1
?>

Number formatting

<?php
echo number_format(1234567.891, 2); // 1,234,567.89
echo number_format(1234567.891, 2, ".", ","); // 1,234,567.89
echo base_convert("ff", 16, 10); // 255
echo decbin(255);    // 11111111
echo dechex(255);    // ff
?>

Mini Practice

Write PHP code that:

  1. Uses basic math functions
  2. Generates random numbers
  3. Performs trigonometric calculations
  4. Formats numbers with separators

Up Next

In the next lesson, you'll learn about Namespaces — organizing code.

Related Topics

Frequently Asked Questions about Math

What is Math in PHP?

Math is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Math?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Math.

Why is Math important in PHP?

Math is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.