HTML and PHP Resources

Short easy to follow tutorials & more…

203: Introduction to PHP Operators

| 0 comments

About the Video

An introduction to math operations, grouping operations and string concatenation.
Length: 11:14
Level: Beginner

Video Notes

Math Operators

  • plus(+) and minus(-)
    • Addition and subtraction (Math)
  • asterisk(*) and forward slash (/)
    • Multiplication and division (Math)
  • Modulus Operator (%)
    • Returns the remainder of a division operation

example_operators.php:

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
$number1 = 5;
$number2 = 3;
$br = "<br>";
echo $number1 + $number2 , $br; // 5 + 3
echo $number1 - $number2 , $br; // 5 - 3
echo $number1 * $number2 , $br; // 5 * 3
echo $number1 / $number2 , $br; // 5 / 3
echo $number1 % $number2 , $br; // Remainder of 5 / 3
?>

Post-Increment & Post-Decrement

  • Use the value of the variable then add/subtract one
  • $a++;
  • $a–;

Pre-Increment & Pre-Decrement

  • Add/Subtract one then use the value of the variable
  • ++$a;
  • –$a;

example_pre_post.php:

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
$number1 = 1;
$number2 = 1;
$br = "<br>";
echo $number1++ , $br; // Use then Append
echo ++$number2 , $br; // Append then use
$number1 = 1;
$number2 = 1;
echo $number1-- , $br; // Use then Append
echo --$number2 , $br; // Append then use
?>

Specifying order

  • Parenthesis specify order of operations
    • (1 + 2) * 3 = 9
    • 1 + 2 * 3 = 7
  • Grouping Operations
    • (3 * ( ( 1 + 2 ) / 2 ))

String Operator

  • Concatenation Operator ( . )
    • Joins two strings end to end
    • Used to append additional text to an existing string
    • Strictly a string operation
  • Note: The dot is also used when specifying decimals.

example_concatanation.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$word1 = 'Hello';
$word2 = 'World';
$word3 = 'Bye!';
$space = ' ';
$br = '<br>';
$result = $word1 . $space . $word2 . $br;
echo $result . $word3;
?>

Summary

  • You can use any of the standard math symbols to do math
  • Plus, minus, division, multiplication
  • Modulus is a special operation
  • Parenthesis are used to group operation and control execution
  • Join string using concatenation operator

Leave a Reply

Required fields are marked *.