Home Linux HTML/CSS PHP React VR T-shirt Shop Blog PHP Fiddle

Intro to PHP: Math Operators





Math Operators are used to perform numeric calculations. It is pretty much just like in grammar school math class.

At the bottom of this page there is a code editor pre-loaded with the lesson's code.
Quick Copy Boxes

Addition: $a + $b

        
            $hrsPlayedMon = 10;
            $hrsPlayedTues = 9;
            $hrsTotal = $hrsPlayedMon + $hrsPlayedTues;
            echo $hrsTotal;
            
          

➼ $hrsPlayedMon is a variable that repersents how many hours Commander Bob played video games on Monday. He played 10 hours.
$hrsPlayedTues is a variable that repersents the number of hours Commander Bob played video games on Tuesday. He played 9 hours.
$hrsTotal is a variable that repersents that number of hours Commander Bob played on Monday (10) plus the number of hours he played on Tuesday (9). He played a total of 19 hours between Monday and Tueday.
echo $hrsTotal; will print the value of $hrsTotal
Output: 19



Subtraction: $a - $b

      
          $hrsDifference = $hrsPlayedMon - $hrsPlayedTues;
          echo $hrsDifference;
          
        

$hrsDifference is a variable that repersents the number of hours Comander Bob played on Monday (10) minus the number of hours he played on Tuesday (9).
echo $hrsDifference; Will print the value of $hrsDifference
Output: 1


Multiplication: $a * $b

        
            define("NUMBER_WEEK_DAYS", 7);
            $weekMultiple = NUMBER_WEEK_DAYS  * $hrsPlayedMon;
            echo $weekMultiple;
            
          

NUMBER_WEEK_DAYS is a constant that equals 7.
$weekMultiple is a variable used to predict how many hours Commander Bob will play video games during the week. It multiplies NUMBER_WEEK_DAYS (7) and $hrsPlayedMonday (10). This is probably not the best prediction algorithm, but I think it is sufficent for our example.
echo $weekMultiple; will print the value of $weekMultiple
Output: 70


Division: $a / $b

          
              $daysCounter = 2;
              $avgDailyHours $hrsTotal / $daysCounter
              echo $avgDailyHours;
              
            

$daysCounter is a variable that repersents how many days we have been tracking Commander Bob's video game hours. We have data for Monday and Tuesday, so I set $daysCounter equal to 2.
$avgDailyHours is a variable that calculates the average number of hours that Commander Bobby plays per day. It is equal to $hrsTotal (19) divided by $daysCounter (2).
echo $avgDailyHours; will print the value of $avgDailyHours
Output: 9.5


Exponents: $a ** $b

An exponent repersents how many times you should multiple the base number by itself.
Example: 34,which in PHP is written 3 ** 4, equals 3*3*3*3, which equals 81. We say 3 ** 4 as 'three to the fourth power'. 3 is the base number and 4 is the exponent. If you do not understand what an exponent is, you might want to visit this page: Algebra Class: Exponents.


      
          $monSquared = $hrsPlayedMon ** 2;
          echo $monSquared;
          
        

$monSquared is a variable that repersents $hrsPlayedMon (10) to the second power. (10 ** 2)
echo $monSquared; will print the value of $monSquared
Output: 100


Negation: - $a

Negation means getting the opposite. The opposite of a possitive number would be negative. The opposite of a negative number would be possitive. The minus symbol (-) is used to show negation
Example 1: $a = 3; $b = -$a; => $b = -3
Example 2: $a = -5; $b = -$a; => $b = 5.


        
            $monOpposite = - $hrsPlayedMon;
            echo $monOpposite;
            
          

$monOpposite is a variable that repersents the opposite of $hrsPlayedMon.
echo $monOpposite; will print the value of $monOpposite
Output: -10


Modul: Remainder of $a % $b

Modul will find the remainder of two numbers when they are divided. The remainder is basically what is left after 2 numbers are divided.
# Example 1: 19 / 3 = 6 1/3, or 6 remainder 1, modul is 1
# Example 2: 11 / 4 = 2 3/4, or 2 remainder 3, modul is 3
(if you don't understand remainders, try visiting Math is fun: Remainders


          
              $daysCounter = 2;
              echo $hrsTotal % $daysCounter;
              
            

$daysCounter is intialized at 2.
echo $hrsTotal % $daysCounter; will print the remainder when $hrsTotal(19) is divided by $daysCounter (2).
Output: 1


Increment

The increment operator adds one to the value of a variable


Post-increment: Returns $a, then increments $a by one

To give the following example some context, let's say you are writing code for an online browser game.


        
            $currentLevel = 1;
            echo 'You completed level: ' .  $currentLevel ++;
            echo "\n";
            echo "You are now on level " .  $currentLevel;
            
          

$currentLevel represents the current level being played. Its value is initialized at 1.
At the end of each level you write code to tell the player what level they completed and then increment (add 1) to the game level:
echo 'You completed level: ' . $currentLevel++; This code will print 'You completed level: ' followed by the value of $currentLevel. Then it will add 1 to the value of $currentLevel.
Output: You completed level: 1 *Value of $currentLevel after the echo statement: 2
echo "\n"; inserts a line break
Now you write code to let the player know what level they are about to start:
echo 'You are now on level ' . $currentLevel; will print 'You are now on level ' followed by the value of $currentLevel.
Output: You are now on level 2


Pre-increment: Increments $a by one, then returns $a.

    
        $currentLevel = 1;
        echo ++$currentLevel;
        echo " " . ++$currentLevel;
        
      

$currentLevel = 1; The variable $currentLevel is intialized back at 1.
echo ++$currentLevel; $currentLevel will be incremented, then printed
Output: 2
echo " " . ++$currentLevel; will print a blank space, increment $currentLevel, then print the value of $currentLevel
Output: 3

Decrement

Decrement subtracts one from the value. It works simularly to increment, but subtracts instead of adds.


So, you are still working on that online browser game. You have to write code to keep track of how many lives the player has remaining. Let's look at the difference between pre- and post- decrement.


Post-decrement: Returns $a, then decrements $a by one


 
     $livesLeft = 3;
     echo $livesLeft-- . " ";
     echo $livesLeft-- . " ";
     echo $livesLeft-- . " ";
     
   

$livesLeft = 3; The player starts with 3 lives.
echo $livesLeft-- . " "; Will print the value of $livesLeft, then decrement it.
Output: 3
echo $livesLeft-- . " "; Will print the value of $livesLeft, then decrement it.
Output: 2
echo $livesLeft-- . " "; Will print the value of $livesLeft, then decrement it.
Output: 1


Pre-decrement: Decrements $a by one, than returns $a


 
     $livesLeft = 3;
     echo --$livesLeft . " ";
     echo --$livesLeft . " ";
     echo --$livesLeft . " ";
     
   

$livesLeft = 3; $livesLeft is intialized back at 3.
echo --$livesLeft . " "; Decrements $livesLeft then prints the value of $livesLeft Output: 2
echo --$livesLeft . " "; Decrements $livesLeft then prints the value of $livesLeft Output: 1
echo --$livesLeft . " "; Decrements $livesLeft then prints the value of $livesLeft Output: 0


Think about how you would want the $livesLeft code to work. Do you think you would pre-decrement or post-decrement?

Applied Assignment

Background:
Imagine you live in a dark and dreary post-apocalyptic Earth. Earth has been taken over by aliens. Due to their bug-like apperance, the aliens are nicknamed "bugs". As a commander in the human resistance, and a web developer, you provide a shining light of hope to Earth's orginally inhabitant.
Assignment:
You are writing code to keep track of bugs living in your district. Write the following statements in PHP code:
Example:
There were 20 bugs, then you killed 5


    // Initialize Variables
    $bugs = 20;
    $bugsKilled = 5;
    // Number of bugs left
    $bugs = $bugs - $bugsKilled;
  

Statements:
1) There are 10 bugs on the south-side and 15 bugs on the north-side.
2) You and your squad encounter 10 bugs. Each bullet fired killed 1 bug. 7 bullets were fired
3) A ship just landed with 11 bugs. There of your cadets found the landing site.
Each cadet killed 3 bugs. You have to kill the remainder.
4) 100 bugs have arrived on Eath. 10% of them enter your district.
5) Each TNT explosive kills 5 bugs. Two TNT explosives were used on the bugs.

Make sure to play around with your variables and statements in the code editor box below.




If you find my tutorials helpful, please consider donating to support my free web development resources.

The more money I raise, the more content I can produce.

Thank you,
Commander Candy

DONATE

Check out my blog:

Coding Commanders Blog

Watch the Coding Commanders LAMP Animation:

Coding Commanders: Episode 1



Follow Coding Commanders on:

YouTube

GitHub

Facebook

Instagram

Twitter

Back to Previous Lesson | Continue to Next Lesson