Setting server for first time to deploy PHP application to cloud

Apache

  • sudo apt-get update
  • sudo apt-get install apache2

Click Here for more details.

MySql

  • sudo apt-get update
  • sudo apt-get install mysql-server
  • mysql_secure_installation

Click Here for more details.

Composer

  • sudo apt-get update
  • sudo apt-get install composer

Click Here for more details.

PHP

  • sudo add-apt-repository ppa:ondrej/php
  • sudo apt-get update
  • sudo apt-get install php7.1 php7.1-common
  • sudo apt-get install php7.1-curl php7.1-xml php7.1-zip php7.1-gd php7.1-mysql php7.1-mbstring

Click Here for more details.

Upgrade from PHP 7.0 to PHP 7.1

Add Ondrejs PPA Repo

PPA’s or Personal Package Archive, is a collection of software not included in Ubuntu by default. Typically these repositories focus on a single program, but they can include more depending on the person maintaining them. Ondřej Surý has created this PPA which has the latest versions of PHP in it. Lets add it to your system, and update to get a list of all the software we can install.

$ sudo add-apt-repository ppa:ondrej/php
$ sudo apt-get update

Install PHP 7.1

Lets stop our server first, then install PHP 7.1.

$ service apache2 stop
$ sudo apt-get install php7.1 php7.1-common

We’ll also install some extra packages for our PHP installation – these are needed for Laravel and Composer!

$ sudo apt-get install php7.1-curl php7.1-xml php7.1-zip php7.1-gd php7.1-mysql php7.1-mbstring php7.1-mysql

Once that is done, lets check PHP is updated on the CLI

$ php -v

If the first row looks like this, we’ve done good so far! PHP 7.1.11-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Oct 27 2017 13:49:56) ( NTS )

Remove PHP 7.0

Now we have PHP7.1, lets get rid of PHP7.0

$ sudo apt-get purge php7.0 php7.0-common

Once this has been done, I usually restart the server.

$ sudo shutdown -r now

Make PHP7.1 used by Apache

Finally, we need to tell Apache to use PHP7.1 now PHP 7.0 is not being used. Lets enable the PHP mod!

$ a2enmod php7.1
$ service apache2 restart

Thats it – PHP should now be using PHP 7.1 – enjoy your amazing new features such as function return types and multiple error catch’s! If you are having issues, feel free to prod me on Twitter at @bhaktaraz

Detect OnePlus5 in Ubuntu in MTP mode

So if you have connected OnePlus 5 to Ubuntu, you will notice that you can only see “OnePlus Drivers” as mounted but you cannot access the internal memory using MTP, although ptp works!

So here is what you need to do to make it possible

1. Enable Developer options in Settings
2. Enable ADB ( this needs to be enabled else, mtp doesnt work )
3. Open a terminal window and follow this :
– we will edit 2 files and add some lines in them. My preferred editor is vim. you may use nano / emacs etc.

COMMAND :

sudo vim /lib/udev/rules.d/69-mtp.rules

ADD LINE :

ATTR{idVendor}==”2a70″, ATTR{idProduct}==”9011″, SYMLINK+=”libmtp-%k”, ENV{ID_MTP_DEVICE}=”1″, ENV{ID_MEDIA_PLAYER}=”1″

save and exit

COMMAND :

sudo vim /etc/udev/rules.d/51-android.rules

ADD LINE : 

ATTR{idVendor}==”2a70″, ATTR{idProduct}==”9011″, MODE=”0666″

save and exit

COMMAND :

sudo service udev restart

Now disconnect and reconnect your phone, you will have “Android Device” as the mtp device.

If you still cannot see, reboot and try to see if the device is now visible!

Thankyou!

PHP – Predefined Variables

PHP provides a large number of predefined variables to any script which it runs. PHP provides an additional set of predefined arrays containing variables from the web server the environment, and user input. These new arrays are called superglobals −

All the following variables are automatically available in every scope.

PHP Superglobals

Sr.No Variable & Description
1 $GLOBALS

Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables.

2 $_SERVER

This is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these. See next section for a complete list of all the SERVER variables.

3 $_GET

An associative array of variables passed to the current script via the HTTP GET method.

4 $_POST

An associative array of variables passed to the current script via the HTTP POST method.

5 $_FILES

An associative array of items uploaded to the current script via the HTTP POST method.

6 $_REQUEST

An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.

7 $_COOKIE

An associative array of variables passed to the current script via HTTP cookies.

8 $_SESSION

An associative array containing session variables available to the current script.

9 $_PHP_SELF

A string containing PHP script file name in which it is called.

10 $php_errormsg

$php_errormsg is a variable containing the text of the last error message generated by PHP.

Server variables: $_SERVER

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these.

Sr.No Variable & Description
1 $_SERVER[‘PHP_SELF’]

The filename of the currently executing script, relative to the document root

2 $_SERVER[‘argv’]

Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.

3 $_SERVER[‘argc’]

Contains the number of command line parameters passed to the script if run on the command line.

4 $_SERVER[‘GATEWAY_INTERFACE’]

What revision of the CGI specification the server is using; i.e. ‘CGI/1.1’.

5 $_SERVER[‘SERVER_ADDR’]

The IP address of the server under which the current script is executing.

6 $_SERVER[‘SERVER_NAME’]

The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

7 $_SERVER[‘SERVER_SOFTWARE’]

Server identification string, given in the headers when responding to requests.

8 $_SERVER[‘SERVER_PROTOCOL’]

Name and revision of the information protocol via which the page was requested; i.e. ‘HTTP/1.0’;

9 $_SERVER[‘REQUEST_METHOD’]

Which request method was used to access the page; i.e. ‘GET’, ‘HEAD’, ‘POST’, ‘PUT’.

10 $_SERVER[‘REQUEST_TIME’]

The timestamp of the start of the request. Available since PHP 5.1.0.

11 $_SERVER[‘QUERY_STRING’]

The query string, if any, via which the page was accessed.

12 $_SERVER[‘DOCUMENT_ROOT’]

The document root directory under which the current script is executing, as defined in the server’s configuration file.

13 $_SERVER[‘HTTP_ACCEPT’]

Contents of the Accept: header from the current request, if there is one.

14 $_SERVER[‘HTTP_ACCEPT_CHARSET’]

Contents of the Accept-Charset: header from the current request, if there is one. Example: ‘iso-8859-1,*,utf-8’.

15 $_SERVER[‘HTTP_ACCEPT_ENCODING’]

Contents of the Accept-Encoding: header from the current request, if there is one. Example: ‘gzip’.

16 $_SERVER[‘HTTP_ACCEPT_LANGUAGE’]

Contents of the Accept-Language: header from the current request, if there is one. Example: ‘en’.

17 $_SERVER[‘HTTP_CONNECTION’]

Contents of the Connection: header from the current request, if there is one. Example: ‘Keep-Alive’.

18 $_SERVER[‘HTTP_HOST’]

Contents of the Host: header from the current request, if there is one.

19 $_SERVER[‘HTTP_REFERER’]

The address of the page (if any) which referred the user agent to the current page.

20 $_SERVER[‘HTTP_USER_AGENT’]

This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586).

21 $_SERVER[‘HTTPS’]

Set to a non-empty value if the script was queried through the HTTPS protocol.

22 $_SERVER[‘REMOTE_ADDR’]

The IP address from which the user is viewing the current page.

23 $_SERVER[‘REMOTE_HOST’]

The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.

24 $_SERVER[‘REMOTE_PORT’]

The port being used on the user’s machine to communicate with the web server.

25 $_SERVER[‘SCRIPT_FILENAME’]

The absolute pathname of the currently executing script.

26 $_SERVER[‘SERVER_ADMIN’]

The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file.

27 $_SERVER[‘SERVER_PORT’]

The port on the server machine being used by the web server for communication. For default setups, this will be ’80’.

28 $_SERVER[‘SERVER_SIGNATURE’]

String containing the server version and virtual host name which are added to server-generated pages, if enabled.

29 $_SERVER[‘PATH_TRANSLATED’]

Filesystem based path to the current script.

30 $_SERVER[‘SCRIPT_NAME’]

Contains the current script’s path. This is useful for pages which need to point to themselves.

31 $_SERVER[‘REQUEST_URI’]

The URI which was given in order to access this page; for instance, ‘/index.html’.

32 $_SERVER[‘PHP_AUTH_DIGEST’]

When running under Apache as module doing Digest HTTP authentication this variable is set to the ‘Authorization’ header sent by the client.

33 $_SERVER[‘PHP_AUTH_USER’]

When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the username provided by the user.

34 $_SERVER[‘PHP_AUTH_PW’]

When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the password provided by the user.

35 $_SERVER[‘AUTH_TYPE’]

When running under Apache as module doing HTTP authenticated this variable is set to the authentication type.

PHP – Strings

They are sequences of characters, like “PHP supports string operations”.

NOTE − Built-in string functions is given in function reference PHP String Functions

Following are valid examples of string

$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.

<?php
   $variable = "name";
   $literally = 'My $variable will not print!\\n';
   
   print($literally);
   print "<br />";
   
   $literally = "My $variable will print!\\n";
   
   print($literally);
?>

This will produce the following result −

My $variable will not print!\n
My name will print!\n

There are no artificial limits on string length – within the bounds of available memory, you ought to be able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in “this”) are preprocessed in both the following two ways by PHP −

  • Certain character sequences beginning with backslash (\) are replaced with special characters
  • Variable names (starting with $) are replaced with string representations of their values.

The escape-sequence replacements are −

  • \n is replaced by the newline character
  • \r is replaced by the carriage-return character
  • \t is replaced by the tab character
  • \$ is replaced by the dollar sign itself ($)
  • \” is replaced by a single double-quote (“)
  • \\ is replaced by a single backslash (\)

String Concatenation Operator

To concatenate two string variables together, use the dot (.) operator −

<?php
   $string1="Hello World";
   $string2="1234";
   
   echo $string1 . " " . $string2;
?>

This will produce the following result −

Hello World 1234

If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string.

Between the two string variables we added a string with a single character, an empty space, to separate the two variables.

Using the strlen() function

The strlen() function is used to find the length of a string.

Let’s find the length of our string “Hello world!” −

<?php
   echo strlen("Hello world!");
?>

This will produce the following result −

12

The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)

Using the strpos() function

The strpos() function is used to search for a string or character within a string.

If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE.

Let’s see if we can find the string “world” in our string −

<?php
   echo strpos("Hello world!","world");
?>

This will produce the following result −

 6

As you see the position of the string “world” in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.

PHP – Arrays

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

  • Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
  • Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
  • Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices

NOTE − Built-in array functions is given in function reference PHP Array Functions

Numeric Array

These arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero.

Example

Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function reference.

<html>
   <body>
   
      <?php
         /* First method to create array. */
         $numbers = array( 1, 2, 3, 4, 5);
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
         
         /* Second method to create array. */
         $numbers[0] = "one";
         $numbers[1] = "two";
         $numbers[2] = "three";
         $numbers[3] = "four";
         $numbers[4] = "five";
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
      ?>
      
   </body>
</html>

This will produce the following result −

Value is 1 
Value is 2 
Value is 3 
Value is 4 
Value is 5 
Value is one 
Value is two 
Value is three 
Value is four 
Value is five 

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.

NOTE − Don’t keep associative array inside double quote while printing otherwise it would not return any value.

Example

<html>
   <body>
      
      <?php
         /* First method to associate create array. */
         $salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
         
         echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
         echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
         echo "Salary of zara is ".  $salaries['zara']. "<br />";
         
         /* Second method to create array. */
         $salaries['mohammad'] = "high";
         $salaries['qadir'] = "medium";
         $salaries['zara'] = "low";
         
         echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
         echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
         echo "Salary of zara is ".  $salaries['zara']. "<br />";
      ?>
   
   </body>
</html>

This will produce the following result −

Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

Multidimensional Arrays

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Example

In this example we create a two dimensional array to store marks of three students in three subjects −

This example is an associative array, you can create numeric array in the same fashion.

<html>
   <body>
      
      <?php
         $marks = array( 
            "mohammad" => array (
               "physics" => 35,
               "maths" => 30,	
               "chemistry" => 39
            ),
            
            "qadir" => array (
               "physics" => 30,
               "maths" => 32,
               "chemistry" => 29
            ),
            
            "zara" => array (
               "physics" => 31,
               "maths" => 22,
               "chemistry" => 39
            )
         );
         
         /* Accessing multi-dimensional array values */
         echo "Marks for mohammad in physics : " ;
         echo $marks['mohammad']['physics'] . "<br />"; 
         
         echo "Marks for qadir in maths : ";
         echo $marks['qadir']['maths'] . "<br />"; 
         
         echo "Marks for zara in chemistry : " ;
         echo $marks['zara']['chemistry'] . "<br />"; 
      ?>
   
   </body>
</html>

This will produce the following result −

Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

PHP – Loop Types

Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.

  • for − loops through a block of code a specified number of times.
  • while − loops through a block of code if and as long as a specified condition is true.
  • do…while − loops through a block of code once, and then repeats the loop as long as a special condition is true.
  • foreach − loops through a block of code for each element in an array.

We will discuss about continue and break keywords used to control the loops execution.

The for loop statement

The for statement is used when you know how many times you want to execute a statement or a block of statements.

for loop in Php

Syntax

for (initialization; condition; increment){
   code to be executed;
}

The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.

Example

The following example makes five iterations and changes the assigned value of two variables on each pass of the loop −

<html>
   <body>
      
      <?php
         $a = 0;
         $b = 0;
         
         for( $i = 0; $i<5; $i++ ) {
            $a += 10;
            $b += 5;
         }
         
         echo ("At the end of the loop a = $a and b = $b" );
      ?>
   
   </body>
</html>

This will produce the following result −

At the end of the loop a = 50 and b = 25

The while loop statement

The while statement will execute a block of code if and as long as a test expression is true.

If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.

for loop in PHP

Syntax

while (condition) {
   code to be executed;
}

Example

This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.

<html>
   <body>
   
      <?php
         $i = 0;
         $num = 50;
         
         while( $i < 10) {
            $num--;
            $i++;
         }
         
         echo ("Loop stopped at i = $i and num = $num" );
      ?>
      
   </body>
</html>

This will produce the following result −

Loop stopped at i = 10 and num = 40 

The do…while loop statement

The do…while statement will execute a block of code at least once – it then will repeat the loop as long as a condition is true.

Syntax

do {
   code to be executed;
}
while (condition);

Example

The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10 −

<html>
   <body>
   
      <?php
         $i = 0;
         $num = 0;
         
         do {
            $i++;
         }
         
         while( $i < 10 );
         echo ("Loop stopped at i = $i" );
      ?>
      
   </body>
</html>

This will produce the following result −

Loop stopped at i = 10

The foreach loop statement

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax

foreach (array as value) {
   code to be executed;
}

Example

Try out following example to list out the values of an array.

<html>
   <body>
   
      <?php
         $array = array( 1, 2, 3, 4, 5);
         
         foreach( $array as $value ) {
            echo "Value is $value <br />";
         }
      ?>
      
   </body>
</html>

This will produce the following result −

Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

The break statement

The PHP break keyword is used to terminate the execution of a loop prematurely.

The break statement is situated inside the statement block. It gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.

PHP Break Statement

Example

In the following example condition test becomes true when the counter value reaches 3 and loop terminates.

<html>
   <body>
   
      <?php
         $i = 0;
         
         while( $i < 10) {
            $i++;
            if( $i == 3 )break;
         }
         echo ("Loop stopped at i = $i" );
      ?>
   
   </body>
</html>

This will produce the following result −

Loop stopped at i = 3

The continue statement

The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.

Just like the break statement the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.

PHP Continue Statement

Example

In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed.

<html>
   <body>
   
      <?php
         $array = array( 1, 2, 3, 4, 5);
         
         foreach( $array as $value ) {
            if( $value == 3 )continue;
            echo "Value is $value <br />";
         }
      ?>
   
   </body>
</html>

This will produce the following result −

Value is 1
Value is 2
Value is 4
Value is 5

PHP – Conditional Statements (Decision Making)

The if, elseif …else and switch statements are used to take decision based on the different condition.

You can use conditional statements in your code to make your decisions. PHP supports following three decision making statements −

Decision making statements in PHP

  • if…else statement − use this statement if you want to execute a set of code when a condition is true and another if the condition is not true
  • elseif statement − is used with the if…else statement to execute a set of code if one of the several condition is true
  • switch statement − is used if you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.

The If…Else Statement

If you want to execute some code if a condition is true and another code if a condition is false, use the if….else statement.

Syntax

if (condition)
   code to be executed if condition is true;
else
   code to be executed if condition is false;

Example

The following example will output “Have a nice weekend!” if the current day is Friday, Otherwise, it will output “Have a nice day!”:

<html>
   <body>
   
      <?php
         $d = date("D");
         
         if ($d == "Fri")
            echo "Have a nice weekend!"; 
         
         else
            echo "Have a nice day!"; 
      ?>
   
   </body>
</html>

It will produce the following result −

Have a nice weekend!

The ElseIf Statement

If you want to execute some code if one of the several conditions are true use the elseif statement

Syntax

if (condition)
   code to be executed if condition is true;
elseif (condition)
   code to be executed if condition is true;
else
   code to be executed if condition is false;

Example

The following example will output “Have a nice weekend!” if the current day is Friday, and “Have a nice Sunday!” if the current day is Sunday. Otherwise, it will output “Have a nice day!” −

<html>
   <body>
   
      <?php
         $d = date("D");
         
         if ($d == "Fri")
            echo "Have a nice weekend!";
         
         elseif ($d == "Sun")
            echo "Have a nice Sunday!"; 
         
         else
            echo "Have a nice day!"; 
      ?>
      
   </body>
</html>

It will produce the following result −

Have a nice Weekend!

The Switch Statement

If you want to select one of many blocks of code to be executed, use the Switch statement.

The switch statement is used to avoid long blocks of if..elseif..else code.

Syntax

switch (expression){
   case label1:
      code to be executed if expression = label1;
      break;  
   
   case label2:
      code to be executed if expression = label2;
      break;
      default:
   
   code to be executed
   if expression is different 
   from both label1 and label2;
}

Example

The switch statement works in an unusual way. First it evaluates given expression then seeks a lable to match the resulting value. If a matching value is found then the code associated with the matching label will be executed or if none of the lable matches then statement will execute any specified default code.

<html>
   <body>
      
      <?php
         $d = date("D");
         
         switch ($d){
            case "Mon":
               echo "Today is Monday";
               break;
            
            case "Tue":
               echo "Today is Tuesday";
               break;
            
            case "Wed":
               echo "Today is Wednesday";
               break;
            
            case "Thu":
               echo "Today is Thursday";
               break;
            
            case "Fri":
               echo "Today is Friday";
               break;
            
            case "Sat":
               echo "Today is Saturday";
               break;
            
            case "Sun":
               echo "Today is Sunday";
               break;
            
            default:
               echo "Wonder which day is this ?";
         }
      ?>
      
   </body>
</html>

It will produce the following result −

Today is Monday

PHP – Operator Types

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. PHP language supports following type of operators.

  • Arithmetic Operators
  • Comparison Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (or ternary) Operators

Lets have a look on all operators one by one.

Arithmetic Operators

There are following arithmetic operators supported by PHP language −

Assume variable A holds 10 and variable B holds 20 then −

Show Examples

Operator Description Example
+ Adds two operands A + B will give 30
Subtracts second operand from the first A – B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
Decrement operator, decreases integer value by one A– will give 9

Comparison Operators

There are following comparison operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then −

Show Examples

Operator Description Example
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

Logical Operators

There are following logical operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then −

Show Examples

Operator Description Example
and Called Logical AND operator. If both the operands are true then condition becomes true. (A and B) is true.
or Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. (A or B) is true.
&& Called Logical AND operator. If both the operands are non zero then condition becomes true. (A && B) is true.
|| Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is false.

Assignment Operators

There are following assignment operators supported by PHP language −

Show Examples

Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C – A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A

Conditional Operator

There is one more operator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax −

Show Examples

Operator Description Example
? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y

Operators Categories

All the operators we have discussed above can be categorised into following categories −

  • Unary prefix operators, which precede a single operand.
  • Binary operators, which take two operands and perform a variety of arithmetic and logical operations.
  • The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.
  • Assignment operators, which assign a value to a variable.

Precedence of PHP Operators

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity
Unary ! ++ — Right to left
Multiplicative * / % Left to right
Additive + – Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= Right to left