Infolinks

Breaking

Adsense

Tuesday, July 19, 2016

Operators in PHP Tutorials for Beginners

Operators are used to operate on values. It might be to add, compare, or even assign values to variables.

There are four kinds of operators in PHP.

  1. Arithmetic Operator
  2. Assignment Operator
  3. Comparison Operator
  4. Logical Operator.

Arithmetic Operators

Operators to perform arithmetic or mathematical operations on numbers either to
ADD +, SUBTRACT -, DIVIDE /, MULTIPLY *, MODULUS % (returns the remainder of the division operation), INCREMENT ++ and DECREMENT --.

Examples:

<?php  
  $a=500;
  $b=100;
  $c=$a+$b;
  echo $c;
?>

Output is 600.

<?php
  $a=(95+90)/2;
  echo $a;
?>

Output is 92.5. 95+90 is 185/2 

<?php
  $a=1; 
  echo $a++;
?>
Output is 2.

<?php
  $a=9%2;
  echo $a;
?>
Output is 1. 9/2 is 4 remainder is 1.

In arithmetic operation, they follow the PEMDAS for its order of operations. Parenthesis, Exponent, multiplication & division, addition & subtraction. Multiplication and division have the same order of operations, same with addition and subtraction. You need to perform operations from left to right.

Assignment Operators

Is used to assign values to variables in php. It can also add to or subtract from a current value. 
=, +=, -=, *=, /=, .=, %=.

Example:

<?php
  $a=10;
  $a.=5;//value of $a is 105. equivalent to $a=$a.5;
  $b+=5; //equivalent to $b=$b+5;

?>

Comparison Operators

Compare two values and return either true or false. You can then perform actions based on the returned value.
== is equal to, != not equal, <> not equal, > is greater than, < is less than, >= is greater than or equal, <= is less than or equal.

Example:

10==8 will return false
10>8 will return true
10<8 will return false
10>=8 will return true
10<=8 will return false
10!=8 will return true
10<>8 will return true

Logical Operators

Determine the status of conditions and returns a boolean value (true or false).
&& and, || or, ! not

$a=2;
$b=5;
if ($a<5 && $b>2) //returns true since 2<5 is true and 5>2 is also true.

Use && and if you want to meet all conditions and returns true. Once, one condition is not met, the output is false. && and is usually used in login form which username and password should be correct to be able to log in in your account.

if ($username=="admin" || $password=="admin")
or is not used in logging in since if a user has a correct username but wrong password still it can login to the system or vice versa. 

! not is used to negate a certain operation
if (!$a==$b) //will return true
read as $a is not equal to $b.

Watch out for more articles related to programming and even systems administration. Please do hit the like button on the right sidebar of this page.

Operators in PHP Tutorials for Beginners

No comments:

Post a Comment

Adbox