PHP Basics tutorial Operators

 

 

Learn PHP Operators

 PHP provides different types of operators. In this tutorial, we discuss some of the operators that we use in coding very frequently.

coding-zon-php-basics-operators.jpg
 

 

Table of Contents

  1. Arithmetic Operators
  2. Assignment Operators.
  3. Comparison Operators 
  4. Logical Operators.
  5. Incrementing/Decrementing Operators.
  6. String Operators

 

 

Using different types of Operator in PHP

1. Arithmetic Operators [ + - * / % ] in PHP

  • addition(+)
  • subtraction(-) 
  • multiply(*)
  • division(/)
  • modular(%)

 

<?php
 
print (10 + 20 + 30);
 
?> 
 
Ex2:
 
<?php
 
$num1 = 10;
$ num2= 20;
$total = $ num1 + $ num2;
print 'Total = ' . $total;
 
?>


Operator precedence

Order of evaluation of an expression

1) / * %
2) + -
3) = 
 
 

ex:

a * ( b+c/d ) * 22


the correct way is:

( a*b ) + ( c/d ) * 22

 

According to the expression first it goes to division and finally goes to multiplication addition, at last the result is printed.

Ex: a=2, b=3, c=8, d=2


What would be the result.

( 2 * 3 ) + ( 8 / 2 ) * 22 
 
    6     +     4   *   22
    
    6     +     88
 
                =94 
 
Ex2: 
 
  
$total = ( $m1 + $m2 + $m3 ) / 3;

Menu Top

2. Assignment Operators in PHP.

These operators perform the operation and re-assign the result to the same variable.

Types of assignment operators.

 
 
=   $a=10;   // $a value is now 10 
+=  $a+=10   // $a value is now 20 

-=  $a-=5    // $a value is now 5
*=  $a*=5    // $a value is now 50
/=  $a/=2    // $a value is now 5 
 
Ex:
 
 
<?php
 
$a = 10;
 
echo ("$a = ". ($a));  
 
//$a = $a+2; //also written as below with short 
 
$a += 2; // this is equal to ($a = $a+2).
 
echo ("a+=5". ($a)); // this is same as ($a = $a+5).
$a-=5; 
echo ("a-=5". ($a ));  // this is same as ($a = $a+5).
$a*=5; 
echo ("a*=5". ($a)); 
$a/=5
echo ("a/=5". ($a)); 
 
?> 
 


Toc

3. Comparison Operators in PHP.

>  greater than
<  less than
<= less than or equal 
>= greater than or equal 
!= not equal to
== equal to


4. Logical Operators in PHP.

Logical Operators are used to combine one or more conditions.

and → and
or  or
!  not
 
 
 

5. Incrementing/Decrementing Operators in PHP.

  • Increment operator (++)
  • Decrement operator (--)
ex:
 
i=10;
i++;
i 11 i value incremented by 1
 
i--;
i 10 i value decremented by 1
 

6. String Operators in PHP.

In PHP, to concatenate/combine  two string dot(.) operator is used.

<?php
 
$a = "Hello ";
$b = $a . "World!"; // Now $b contains "Hello World!"
 
print $a;
 
$a = "Hello ";
$a .= "World!"; // Here $a contains "Hello World!"
 
print $a;
 
 
?> 
 

 

 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP