PHP Arithmetic Operators

Last updated on

Perhaps you're new to PHP or sharpening your skills and looking to understand how numbers work within this language under the hood of arithmetic operators. In any case, arithmetic operators play an important role in making basic math and calculations possible in PHP. Be it summing totals, averaging values, or working out the result of a more complicated equation, PHP arithmetic operators will form a central part of almost all your code.

In the tutorial below, I’ll introduce each operator in turn, explaining how it works and then showing an example or two, so that there’s no confusion.

Why are PHP arithmetic operators so important?

Let me tell you why PHP arithmetic operators are so crucial before we get into the nitty-gritty. Math, admittedly, may not be the most exciting part of coding, but without these operators, you’d struggle to build any application meant to interact with numbers. Think of an online store tallying totals, a budgeting application summing expenses, or even a game that keeps track of your score—these are just a few examples of where arithmetic operators come in. Once you get a good grasp of them, you can tackle nearly any numeric task PHP throws at you.

Overview of Arithmetic Operators in PHP

Let's break down the basic operators in PHP: addition, subtraction, multiplication, division, modulus, and exponentiation. Each has a specific role, and mastering them will make your code run seamlessly and efficiently.

Here’s a rough list:

OperatorNameDescripion
+=AdditionTo sum two numbers together.
-=SubtractionTo minus two numbers
*=MultiplicationTo multiply numbers together
/=DivisionTo divide two digits
%=ModulusThe first variable is divided by the second one.
**=ExponentiationRefers to the calculated exponentiation

Each of these operators has its own quirks, and they work together in PHP to offer quite a bit of flexibility in number manipulation. You’ll learn about each one in detail in the following section.

Addition Operator (+)

The addition operator is probably the most straightforward—it simply adds two numbers together. The syntax in PHP is straightforward: you place a `+` sign between two values or variables, and PHP returns the sum.

For example:

$firstNumber = 10;
$secondNumber = 20;
$result = $firstNumber + $secondNumber;
echo $result; // outputs 30

Here, PHP takes the values of $firstNumber and $secondNumber, adds them, and assigns the result to $result. This operator is very handy whenever you need to sum several values.

In the following section, you will learn how to switch things around and find a difference using subtraction.

Subtraction Operator (-)

The subtraction operator does what you’d expect: it subtracts one number from another. Like addition, it's easy to use and follows the same syntax, but with the - sign.

Here is an example:

$firstNumber = 30;
$secondNumber = 10;
$result = $firstNumber - $secondNumber;
echo $result; // Outputs 20

Subtraction applies best when finding things like discounts, and differences, or removing items from totals. PHP handles it smoothly, and you can rely on it for basic subtraction tasks within your scripts.

Next, we’ll see how multiplication extends this concept further when you’re working with scaling or proportions.

Multiplication Operator (*)

With multiplication, things start to get a bit more powerful. You can use the * symbol to multiply two numbers in PHP. This is pretty handy for all kinds of calculations where you need to scale something up or work out proportions.

For example:

$firstNumber = 5;
$secondNumber = 4;
$result = $firstNumber * $secondNumber;
echo $result; // Output 20

Multiplication finds applications in finances, inventory, or any place where you’re scaling numbers. It’s an excellent operator when amplifying values or adjusting quantities.

Next, we discuss division, a key operator for breaking down a number or finding an average.

Division Operator (/)

Division, as you might expect, divides one number by another. The syntax is as simple as using the / symbol between two values. It’s perfect for working with averages, unit rates, and quantities that need division into parts.

Look at this:

$firstNumber = 20;
$secondNumber = 4;
$result = $firstNumber / $secondNumber;
echo $result; // Outputs 5

Division is incredibly useful for any activity involving splitting or dividing quantities. Just be careful—PHP will give an error if you attempt to divide by zero, so keep that in mind when writing your scripts.

Moving on, we’ll cover a different operator that’s useful for finding remainders: the modulus.

Modulus Operator (%)

The modulus operator, represented by %, returns the remainder of a division. It might seem niche, but it’s quite helpful for specific tasks. Need to check if a number is even or odd? The modulus operator can help.

For example:

$firstNumber = 10;
$secondNumber = 3;
$result = $firstNumber % $secondNumber;
echo $result; // Outputs 1

In this case, 10 divided by 3 gives a quotient of 1. That remainder is what the modulus operator picks up. The modulus operator is useful for establishing loops, defining cycles, or testing divisibility.

In this section, you’ll learn about the exponentiation operator, helpful for calculations involving powers.

Exponentiation Operator (**)

Exponentiation might sound complex, but it simply raises one number to the power of another. This ** operator allows you to perform exponential calculations in a single line, which can be crucial for financial and scientific uses where you need growth over time.

Look at this example:

$base = 2;
$exponent = 3;
$result = $base ** $exponent;
echo $result; // Outputs 8

In this example, 2 raised to the power of 3 equals 8. The exponentiation operator is handy for repeated multiplication, such as in calculating compound interest or growth rates.

Next, we’ll explore how these arithmetic operators can be combined for more complex calculations.

Combining Arithmetic Operators in PHP

Once you’re comfortable with each operator on its own, combining them opens up even more possibilities. In PHP, you can combine arithmetic operators in a single line, and PHP follows the standard order of operations you learned in math class (PEMDAS).

Let's see an example:-

$number = 10 + 5 * 2 - 3 / 1;
echo $number; // Outputs 17

PHP handles multiplication and division first, then moves on to addition and subtraction. Knowing the precedence allows you to perform more complex calculations without breaking them into steps.

The following section introduces two more operators that make counting up or down easier.

Combining Arithmetic Operators in PHP

Once you’re comfortable with each operator on its own, combining them opens up even more possibilities. In PHP, you can combine arithmetic operators together in a single line, and PHP follows the standard order of operations you learned in math class (PEMDAS).

Here is an example:

$number = 10 + 5 * 2 - 3 / 1;
echo $number; // Outputs 17

PHP handles multiplication and division first, then moves on to addition and subtraction. Knowing the precedence allows you to perform more complex calculations without breaking them into steps.

The following section introduces two more operators that make counting up or down easier.

Increment (++) and Decrement (--) Operators  

The increment and decrement operators are a quick way to add or subtract 1 from a value. These are useful in loops or other situations where you need to count up or down frequently.

For example:

$count = 5;
$count++;
echo $count; // Outputs 6

Here, ++ increments $count by 1. You could also use -- to subtract 1. They’re great for loop counters and help to simplify code.

In the final section, we’ll summarize what we’ve learned and look at how to leverage these operators in PHP.

Wrapping Up 

That’s a tour of PHP arithmetic operators. If you’ve followed along, you should now be comfortable with addition, subtraction, multiplication, division, modulus, exponentiation, and increment or decrement operations. Each has its unique place, and knowing them will make you more proficient in PHP programming. These operators form the foundation of any dynamic application involving calculations, so getting comfortable with them will set you up for success.

PHP arithmetic operators may seem basic, but they’re the building blocks of many applications. Everything from a simple game keeping track of scores to complex financial applications relies on these very operators to function dynamically. Go ahead and practice them in your code. The more you work with them, the more natural they’ll become, and before long, you’ll be using these operators with ease in everything you build!

Frequently Asked Questions (FAQs)

  • What are PHP arithmetic operators?

    Arithmetic operators in PHP are symbols assigned to perform basic mathematical operations: addition, subtraction, multiplication, division, modulus—which means remainder—and exponentiation, raising to a power. They are essential for carrying out calculations in PHP; hence, their application can range from simple scripts to complex programs.
  • How do you add two numbers in PHP?

    In PHP, when you want to add two numbers, you use the + operator. Example:
    $sum = 10 + 5;
    echo $sum; // Outputs 15
    This addition operator is straightforward and works with both numbers and variables.
  • What is the difference between division (/) and modulus (%) in PHP?

    The division operator (/) returns the quotient of two numbers. The modulus operator (%) returns only the remainder of the division. Example:
    $divisionResult = 10 / 3; // Output: 3.333
    $modulusResult = 10 % 3;  // Outputs 1
    For instance, in this case, 10 / 3 will return 3.333 while 10 % 3 will return the remainder, i.e., 1 only.
  • How does the exponentiation operator () work?

    The exponentiation operator (**) raises one number to the power of another. For example, 2 ** 3 means "2 raised to the power of 3," which equals 8. Here's how it looks in code:
    $result = 2 ** 3;
    echo $result; // Outputs 8
    
  • Can I use more than one arithmetic operator on one line?

    Yes! PHP follows the standard order of operations, so you can use various operators on one line, and PHP will figure out the correct order. For example:
    $result = 10 + 5 * 2 - 3 / 1;
    echo $result; // Outputs 17
    PHP performs multiplication and division before performing addition and subtraction.
  • What is the purpose of the increment (++) and decrement (--) operators?

    The increment (++) and decrement (--) operators add or subtract 1 from the value of a variable. These operators are handy in loops or anywhere you have to count up or down frequently.
    $count = 5;
    $count++;
    echo $count; // Outputs 6
    
  • How do you handle division by zero in PHP?

    In PHP, dividing by zero throws an error, so checking whether the divisor (the number you are dividing by) is zero beforehand is a good idea:
    $divisor = 0;
    if ($divisor != 0) {
        $result = 10 / $divisor;
    } else {
        echo "Cannot divide by zero!";
    }
    This check prevents runtime errors that may stop your script.
  • What happens if I try to concatenate numbers and strings using arithmetic operators?

    PHP will automatically convert strings to numbers if it makes sense for the calculation. Example:
    $result = "10" + 5; // Outputs 15
    However, if the string cannot be converted (e.g., "apple" + 5), PHP will consider the string as zero and may even show a warning.
  • Can I use arithmetic operators on PHP arrays?

    No, arithmetic operators are for numbers, not arrays. If you use them on arrays, it will cause an error. If you want to perform arithmetic on elements of an array, you should access each element individually or use functions intended for arrays.
  • Why should I know PHP arithmetic operators?

    Understand PHP arithmetic operators for dynamic calculations. Learn addition, subtraction, multiplication, division, modulus, and more, with examples and tips.
Share on: