1 of 42

PHP Operators

Operators are used to perform operations on variables and values.

    • Arithmetic operators
    • Assignment operators
    • Comparison operators
    • Increment/Decrement operators
    • Logical operators
    • String operators
    • Array operators

2 of 42

Arithmetic Operators

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y

the power (Introduced in PHP 5.6)

3 of 42

Assignment Operators

The PHP assignment operators are used with numeric values to write a value to a variable.

Assignment Same as... Description

x = y x = y The left operand gets set to the value of the expression on the right

x += y x = x + y Addition

x -= y x = x - y Subtraction

x *= y x = x * y Multiplication

x /= y x = x / y Division

x %= y x = x % y Modulus�

4 of 42

Comparison Operators

The PHP comparison operators are used to compare two values (number or string):

Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y,

and they are of the same type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y,

or they are not of the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than $x >= $y Returns true if $x is greater than or

or equal to equal to $y

<= Less than $x <= $y Returns true if $x is less than or

or equal to equal to $y�

5 of 42

Increment/Decrement Operators

  • The PHP increment operators are used to increment a variable's value.
  • The PHP decrement operators are used to decrement a variable's value.

Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

6 of 42

Logical Operators

The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

Operator Name Example Result

and And $x and $y True if both $x and $y are true

or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true, but not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

7 of 42

String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2

.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1 assignment

8 of 42

PHP Operators(String operators)

Ex1: Ex2:

<!DOCTYPE html>�<html>�<body>��<?php�$txt1 = "Hello";�$txt2 = " world!";�echo $txt1 . $txt2;�?>  ��</body>�</html>

Output: Hello world!

<!DOCTYPE html>�<html>�<body>��<?php�$txt1 = "Hello";�$txt2 = " world!";

$txt1 .= $txt2; �echo $txt1;�?>  ��</body>�</html>

Output: Hello world!

9 of 42

Array operators

The PHP array operators are used to compare arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same key/value pairs

=== Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non-identity $x !== $y Returns true if $x is not identical to $y

10 of 42

PHP Operators(Array operators)

Ex1: + operator Ex2: === operator

<!DOCTYPE html>�<html>�<body>��<?php�$x = array("a" => "red", "b" => "green");  �$y = array("c" => "blue", "d" => "yellow");  ��print_r($x + $y); // union of $x and $y�?>  ��</body>�</html>

Output:

Array ( [a] => red [b] => green [c] => blue [d] => yellow )

<!DOCTYPE html>�<html>�<body>��<?php�$x = array("a" => "red", "b" => "green");  �$y = array("c" => "blue", "d" => "yellow");  ��var_dump($x === $y);�?>  ��</body>�</html>

Output: bool(false)

11 of 42

PHP Control Structures

PHP Control Structures are categorized into two types:

    • Conditional Statements
    • Looping Statements

12 of 42

PHP Control Structures(Conditional Statements)

Conditional statements are used to perform different actions based on different conditions.

In PHP we have the following conditional statements:

  • if statement - executes some code if one condition is true
  • if...else statement - executes some code if a condition is true and another code if that condition is false
  • if...elseif....else statement - executes different codes for more than two conditions
  • switch statement - selects one of many blocks of code to be executed

13 of 42

PHP Control Structures(Conditional Statements)

PHP - The if Statement

The if statement executes some code if one condition is true.

Syntax

if (condition)

{�    code to be executed if condition is true;�}

The example below will output "Have a good day!" if the current time (HOUR) is less than 20:

Example

<?php�$t = date("H");�if ($t < "20") {�    echo "Have a good day!";�}�?>

14 of 42

PHP Control Structures(Conditional Statements)

PHP - The if...else Statement

The if....else statement executes some code if a condition is true and another code if that condition is false.

Syntax

if (condition)

 {�    code to be executed if condition is true;� }

else

{�    code to be executed if condition is false;� }

15 of 42

PHP Control Structures(Conditional Statements)

PHP - The if...else Statement

The example below will output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:

Example:

<?php� $t = date("H");�� if ($t < "20")

{�     echo "Have a good day!";� } 

else 

{�     echo "Have a good night!";� }� ?>

16 of 42

PHP Control Structures(Conditional Statements)

PHP - The if...elseif....else Statement

The if....elseif...else statement executes different codes for more than two conditions.

Syntax:

if (condition)

{�    code to be executed if this condition is true;�} elseif (condition) {�    code to be executed if this condition is true;�} else {�    code to be executed if all conditions are false;�}

17 of 42

PHP Control Structures(Conditional Statements)

PHP - The if...elseif....else Statement

Example:

<?php�$t = date("H");��if ($t < "10")

{�    echo "Have a good morning!";�}

 elseif ($t < "20")

{�    echo "Have a good day!";�} else 

{�    echo "Have a good night!";�}�?>

18 of 42

PHP Control Structures(Conditional Statements)

The switch statement is used to perform different actions based on different conditions.

The PHP switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax:

switch (n)

{�    case label1:�        code to be executed if n=label1;�        break;�    case label2:�        code to be executed if n=label2;�        break;�    case label3:�        code to be executed if n=label3;�        break;�    ...�    default:�        code to be executed if n is different from all labels;�}

19 of 42

PHP Control Structures(Conditional Statements)

Example:

<?php�$favcolor = "red";��switch ($favcolor) 

{�    case "red":�        echo "Your favorite color is red!";�        break;�    case "blue":�        echo "Your favorite color is blue!";�        break;�    case "green":�        echo "Your favorite color is green!";�        break;�    default:�        echo "Your favorite color is neither red, blue, nor green!";� }�?>

20 of 42

PHP Control Structures(Looping Statements)

PHP while loops execute a block of code while the specified condition is true.

PHP Loops:

In PHP, we have the following looping statements:

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

21 of 42

PHP Control Structures(Looping Statements)

The PHP while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax:

while (condition is true)

{�    code to be executed;�}

<?php �$x = 1; ��while($x <= 5)

{�    echo "The number is: $x <br>";�    $x++;�} �?>

22 of 42

PHP Control Structures(Looping Statements)

The PHP do…while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax:

do

{ �    code to be executed;�} while (condition is true) ;

<?php �$x = 1; ��do

{�    echo "The number is: $x <br>";�    $x++;�}  while($x <= 5) ;�?>

23 of 42

PHP Control Structures(Looping Statements)

PHP for loops execute a block of code a specified number of times.

The PHP for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax:

for (init counter; test counter; increment counter)

{�    code to be executed;�}

Parameters:

init counter: Initialize the loop counter value

test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.

increment counter: Increases the loop counter value

24 of 42

PHP Control Structures(Looping Statements)

PHP for loops execute a block of code a specified number of times.

The PHP for Loop

Example: Output:

<?php �for ($x = 0; $x <= 10; $x++)

 {�    echo "The number is: $x <br>";�} �?>

The number is: 0 �The number is: 1 �The number is: 2 �The number is: 3 �The number is: 4 �The number is: 5 �The number is: 6 �The number is: 7 �The number is: 8 �The number is: 9 �The number is: 10 

25 of 42

PHP Control Structures(Looping Statements)

The PHP foreach Loop

**The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax

foreach ($array as $value)

{�    code to be executed;�}

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

26 of 42

PHP Control Structures(Looping Statements)

The PHP foreach Loop

Example

<?php �$colors = array("red", "green", "blue", "yellow"); ��foreach ($colors as $value)

{�    echo "$value <br>";�}�?>

27 of 42

PHP  Functions

The PHP functions are real power of it, it has more than 1000 built-in functions

Def: A function is a block of statements that can be used repeatedly in a program.

28 of 42

PHP User Defined Functions

  • Besides the built-in PHP functions, we can create our own functions.

  • A function will not execute immediately when a page loads.

  • A function will be executed by a call to the function.

29 of 42

Create a User Defined Function in PHP

A user defined function declaration starts with the word "function":

Syntax

function functionName()

{�    code to be executed;�}

30 of 42

Example:

<!DOCTYPE html>

<html>

<body>

<?php

function writeMsg()

{

echo "Hello world!";

}

writeMsg();

?>

</body>

</html>

31 of 42

PHP Function Arguments

Information can be passed to functions through arguments. An argument is just like a variable.

Example:

<?php

function familyName($fname)

{

echo "$fname Refsnes.<br>";

}

familyName("Jani");

familyName("Hege");

familyName("Stale");

familyName("Kai Jim");

familyName("Borge");

?>

OUTPUT:

Jani Refsnes.�Hege Refsnes.�Stale Refsnes.�Kai Jim Refsnes.�Borge Refsnes.

32 of 42

Ex2: function with 2 arguments

<?php

function familyName($fname, $year)

{

echo "$fname Refsnes. Born in $year <br>";

}

familyName("Hege", "1975");

familyName("Stale", "1978");

familyName("Kai Jim", "1983");

?>

Output:

Hege Refsnes. Born in 1975�Stale Refsnes. Born in 1978�Kai Jim Refsnes. Born in 1983

33 of 42

Function with default arguments

<?php

function setHeight($minheight = 50)

{

echo "The height is : $minheight <br>";

}

setHeight(350);

setHeight();

setHeight(135);

setHeight(80);

?>

Output:

The height is : 350 �The height is : 50 �The height is : 135 �The height is : 80 

34 of 42

PHP Functions - Returning values:

<?php

function sum($x, $y)

{

$z = $x + $y;

return $z;

}

echo "5 + 10 = " . sum(5, 10) . "<br>";

echo "7 + 13 = " . sum(7, 13) . "<br>";

echo "2 + 4 = " . sum(2, 4);

?>

output:

5 + 10 = 15�7 + 13 = 20�2 + 4 = 6

35 of 42

PHP- Reading data from web form controls like text boxes, radio buttons, lists etc.

36 of 42

Introduction

  • We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and $_POST.
  • The form request may be get or post.
  • To retrieve data from get request, we need to use $_GET, for post request $_POST.
  • $_GET is an array of variables passed to the current script via the URL parameters.

  • $_POST is an array of variables passed to the current script via the HTTP POST method.

37 of 42

$_GET

  • GET transfers the information through http head location & displays the data on URL address.
  • GET is unsecured.
  • GET may be used for sending non-sensitive data.
  • GET transfers limited amount of data.
  • GET can't upload the file.
  • Because the variables are displayed in the URL, it is possible to bookmark the page.

Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send.

38 of 42

$_POST

  • POST transfers the information through document body.
  • POST is highly secured.

1. POST requests do not remain in the browser history

2. POST requests cannot be bookmarked

  • POST transfers huge amount of data.
  • POST can upload the files.

Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send. Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.

39 of 42

Form.html

<html>

<body>

<form action="welcome.php" method="get">  

Name: <input type="text" name="name"/>  

<input type="submit" value="visit"/>  

</form>  

</body>

</html>

<?php  

$name=$_GET["name"];  

echo "Welcome, $name";  

?>  

welcome.php

Output:

Welcome raj�

40 of 42

Login.html

<form action="login.php" method="post">   

<table>   

<tr>

<td>Name:</td>

<td> <input type="text" name="name"/></td>

</tr>  

<tr>

<td>Password:</td>

<td> <input type="password" name="password"/></td>

</tr>   

<tr>

<td colspan="2"><input type="submit" value="login"/>  </td>

</tr>  

</table>  

</form>   

<?php  

$name=$_POST["name"];  

$password=$_POST["password"];  

 echo "Welcome: $name, your password is: $password";  

?>  

Login.php

41 of 42

42 of 42