Saturday, May 3, 2014

PHP Operators

PHP - Operators

In all programming languages, operators are used to manipulate or perform operations on variables and values. The assignment operator "=" in pretty much every PHP example so far.

There are mainly five types of Operators:-
  • Assignment Operators
  • Arithmetic Operators
  • Comparison Operators
  • String Operators
  • Combination Arithmetic & Assignment Operators

Assignment operators : It used to set a variable equal to a value or set a variable to another variable's value. Such an assignment of value is done with the "=", or equal character. Example:
  • $my_var = 4;
  • $another_var = $my_var; 

PHP Code:

$number1 = 10;
$number1 +=2;  //including +-*/% and all other
echo $number1;

Output:

12
8
20
5
0

Comparison Operators

Comparisons are used to check the relationship between variables and/or values. Comparison operators are used inside conditional statements and evaluate to either true or false. Here are the most important comparison operators of PHP.
Assume: $x = 4 and $y = 5;

String Operators

As we have already seen in the previous Lesson "." is used to add two strings together, or more technically, the period is the concatenation operator for strings.

PHP Code:

$a_string = "Hello";
$another_string = " Billy";
$new_string = $a_string . $another_string;
echo $new_string . "!";

Output:

Hello Billy! 

Arithmetic Operators

PHP Code:

<?php

$number1 = 100;

$number2 = 50;

$number3 = 2;

$result = ($number1+$number2)/$number3;

echo $result;

?>

Pre/Post-Increment & Pre/Post-Decrement

This may seem a bit absurd, but there is even a shorter shorthand for the common task of adding 1 or subtracting 1 from a variable. To add one to a variable or "increment" use the "++" operator:

PHP Code:

$x = 4;
echo "The value of x with post-plusplus = " . $x++;
echo "<br /> The value of x after the post-plusplus is " . $x;
$x = 4;
echo "<br />The value of x with with pre-plusplus = " . ++$x;
echo "<br /> The value of x after the pre-plusplus is " . $x;

Output:

The value of x with post-plusplus = 4
The value of x after the post-plusplus is = 5
The value of x with with pre-plusplus = 5
The value of x after the pre-plusplus is = 5




 

No comments:

Post a Comment