34 PHP – II

Dr S. Abirami

  Learning Objectives

 

This module is intended to learn about the PHP Strings, usage of various PHP operators, different types of PHP functions and PHP Arrays for successful PHP scripts programming and deployment in Web server.

 

1.    PHP String

 

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support.

 

2.   PHP Operators

 

PHP operator is a symbol that is used to perform operations on various operands. For example:

$num=10+20;//+ is the operator and 10, 20 are operands.In the above example, + is the binary operator, 10 and 20 are operands and $num is a variable.Operators are used to perform operations on variables and values.Operators in PHP are similar to those found in many modern C-like programming languages.PHP divides the available set of operators in the following groups:

Arithmetic operators Assignment operators Comparison operators

Increment/Decrement operators Logical operators

String operators Array operators

We can also categorize operators on behalf of operands. Using Operators, they can be categorized in 3 forms:

 

Unary Operators: works on single operands such as ++, — etc.

Binary Operators: works on two operands such as binary +, -, *, / etc.

Ternary Operators: works on three operands such as “?:”.

 

2.1 PHP Arithmetic Operators

  The PHP arithmetic operators are used along with numerical values to perform common arithmetical operations, such as addition, subtraction, multiplication and divisionas shown in Table 1.

 

 

2.2 PHP Assignment Operators

 

The PHP assignment operators are used along with numerical values to assign a value to a variable.The basic assignment operator in PHP is “=”. Different Assignment operators available in PHP script is shown in Table 2.

 

 

2.3 PHP Comparison Operators

 

The PHP comparison operators are used to compare two values (number or string) as shown in Table 3.

 

 

2.4 PHP Increment / Decrement Operators

 

The PHP increment/decrement operators are used to increment/decrement the value of the variable as shown in Table 4.

 

 

2.5 PHP Logical Operators

 

The PHP logical operators are used to combine conditional statements as shown in Table 5.

 

 

2.6 PHP String Operators

 

PHP has two operators that are specially designed to perform operations on strings as shown in Table 6.

 

 

2.7 PHP Array Operators

 

Apart from the PHP Arithmetic and String Operators, it also possess array operators which can be used to compare arrays effectively. A list of PHP Array operators has been listed in the Table 7.

 

   3.    CONDITIONAL STATEMENTS

 

Whenwe write code very often, we want to perform different actions based on various conditions. In those situations, we can use conditional statements in our code to handle.In PHP we have the following conditional statements to handle the situations which require various actions:

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 the many blocks of code to be executed

if Statement: if statement is used to execute some code only if a specified condition is true.

 

Syntax

 

if(condition){

//code to be executed

}

 

Example for if statement:

 

<?php

$num=12;

if($num<100) { echo “$num is less than 100”; }

?>

 

Output: 12 is less than 100

 

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;} }

 

Example for if..else statement:

    <?php

$t = date(“H”);

if ($t < “20”) { echo “Have a good day!”; }

else { echo “Have a good night!”; }

?>

    Output: Have a good night!

 

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;}

 

Example for if..elseif…else statement:

 

<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>

 

Output:

 

The following example output is “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!”

 

Switch Statement:

  Switch statement can be used in situations where we are forced to select one of many blocks of code to be executed.

   Syntax for Switch statement in PHP:

 

switch (n) {

case label1:

code to be executed if n=label1;

break;

case label2:

code to be executed if n=label2;

break;…

default:

code to be executed if n is different from all labels;

}

 

Example of switch Statement:

 

<?php

$num=20;

switch($num){

case 10:

echo(“number is equals to 10”);

break;

case 20:

echo(“number is equal to 20”);

break;

case 30:

echo(“number is equal to 30”);

break;

default:

echo(“number is not equal to 10, 20 or 30”);

} ?>

Based on the case values, corresponding echo statements would get executed.

 

LOOP STATEMENTS:

 

Loop statements in PHP are used to execute the same block of code until the given condition is satisfied. Very often when we write code, we want the same block of code to run a number of times. We can use looping statements in our code to perform this.In PHP we have the following types of looping statements:

   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.

 

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.

 

While Statement :The while statement will execute a block of code if and as long as a condition is true.

 

Syntax of While statement:

     while (condition)

code to be executed;

 

Example of While statement:

 

<?php

$i=1;

while($i<=5) {

echo “The number is ” . $i . “<br />”;

$i++;

} ?>

 

Output:

 

The number is 1 The number is 2 The number is 3 The number is 4

 

do…while Loop Statement :The do…while loop will always execute the block of code once, it will then check the condition, and repeat the loop until the specified condition is true.

 

Syntax of do…while statement:

 

do {

code to be executed;

} while (condition is true);

 

Example:

 

<?php

$n=1;

do{

echo “$n<br/>”;

$n++;

}while($n<=10); ?>

   for Loop Statement :PHP for loop statement can be used to traverse a set of code for the specified number of times.It can be used only if the number of iterations is known, otherwise while loop has to be used.

    Syntax – for Loop statement:for(initialization; condition; increment/decrement){ //code to be executed

}

 

Example – for Loop statement:

 

<?php

for ($i = 1; $i <= 10; $i++)

{

echo $i;

}

?>

 

for each Loop Statement :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;

}

 

Example- for each Loop Statement:

 

<?php

$season=array(“summer”,”winter”,”spring”,”autumn”);

foreach( $season as $arr )

{

echo “Season is: $arr<br />”;

}

?>

 

Break Statements: PHP break statement breaks the execution of current for, while, do-while, switch and for-each loop. If we use a break statement inside inner loop, it breaks the execution of inner loop only.

 

Syntax:

 

jump statement;

break;

  Example for break statement:

 

<?php

for($i=1;$i<=10;$i++){

echo “$i<br/>”;

if($i==5){ break; }

}

?>

 

Continue Statements: The continue statement is used within looping structures to skip the rest of the current loop iteration and continue the execution at the point of condition evaluation and then it begins the next iteration.

 

Example:

 

<?php

$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);

foreach( $array as $value )

{

if( $value == 3 )

continue;

echo “Value is $value <br />”;

}

?>

 

4.   PHP FUNCTIONS

 

PHP function is a piece of code that can be reused many times. This can take input as an argument list and return values. There are thousands of built-in functions in PHP.In PHP, we can define Conditional function, Function within Function and Recursive function also.

 

4.1 User Defined Functions

 

Besides the built-in PHP functions, we can create our own functions which are known as user defined functions. A function is a block of statements that can be used repeatedly in a program.A function will not execute immediately when a page loads but it will be executed when a function is invoked.A user defined function declaration starts with the word “function”.

 

Syntax:

 

function functionName()

{

code to be executed;

}

 

Example:

   <?php

functionsayHello()

{

Echo “Hello PHP Function”;

}

sayHello();//calling function

?>

   Output:Hello PHP Function

 

Rules for defining a function:

A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

 

It can’t be started with numbers or special symbols.

 

PHP Function Arguments: Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right.PHP supports passing arguments to the functions using anyone of the types: pass by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported in PHP. The example given below passes a single argument to PHP function

 

<?php

functionsayHello($name){

echo “Hello $name<br/>”; }

sayHello(“Vimal”);  sayHello(“John”);

?>

 

PHP Call ByReference: In this method, the value passed to the function does not modify the actual value by default (call by value). But the value can be modified by passing value as a reference.By default, value passed to the function is call by value. To pass value as a reference, it is advised to use ampersand (&) symbol before the argument name.

 

Example:

 

<?php

function adder(&$str2) {

$str2 .= ‘Call By Reference’; }

$str = ‘Hello ‘; adder($str);  echo $str;

?>

 

Output:Call By Reference

   PHP Default Argument Value:The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument.

 

Example:

 

<?php

functionsetHeight($minheight = 50) {

echo “The height is : $minheight<br>”;            }

setHeight(350);

setHeight(); // will use the default value of 50

setHeight(135);

?>

 

PHP Functions – Returning values: Apart from the functions defined above, functions can also be defined and used to return values.

 

Example:

 

<?php

function add($x,$y)

{

$total = $x + $y;

return $total;

}

echo “1 + 16 = ” . add(1,16);

?>

 

Output: 1 + 16 = 17

 

PHP Call By Value: PHP allows the user to call function by value and reference both.In case of PHP call by value, actual value does not get altered, if it is modified inside the function.

 

Example:

 

<?php

function adder($str2) {

$str2 .= ‘Call By Value’;

}

$str = ‘Hello ‘;

adder($str);

echo $str;

?>

 

Output:Hello

  PHP Variable Length Argument Function: PHP supports the concept of variable length argument functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.Variable functions won’t work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Wrapper functions can be utilized to make use of any of these constructs as variable functions.

 

Variable length argument function example:

 

<?php

function foo() {

echo “In foo()<br />\n”;

}

function bar($arg = ”) {

echo “In bar(); argument was ‘$arg’.<br />\n”; }

//  This is a wrapper function around echo functionechoit($string) { echo $string; } $func = ‘foo’;

$func();  // This calls foo()

$func = ‘bar’;

$func(‘test’); // This calls bar()

$func = ‘echoit’;

$func(‘test’); // This calls echoit()

?>

 

Advantage of using PHP Functions:

 

Code Reusability Less Code

Easy to understand.

 

5.  PHP ARRAYS

 

An array stores multiple values in one single variable.Arrays have names that begin with $.PHP array is an ordered map (contains value on the basis of key) which is used to hold multiple values of similar type in a single variable. The element type is not specified and it can mix the data types too.Suppose we need to store roll numbers of 100 students then we can use array variable roll which can store 100 values in single variable with index.

 

Example:

Create an Array in PHPusing the array() language construct. It takes any number of comma-separated key => value pairs as arguments.

    Syntax:array();

array(key => value, key2 => value2, key3 => value3, …);

Example:$shapes = array(“square”,”rectangle”,”circle”,”oval”);

 

PHP Array Types

 

There are 3 types of array in PHP.

  • Indexed Array – An array with a numeric index
  • Associative Array – An array with strings as index. This stores element values in association with key values rather than in a linear index order.
  • Multidimensional Array – An array containing one or more arrays

PHP Indexed Arrays:PHP index is represented by number which starts from 0. We can store number, string and objects in the PHP array. All PHP array elements are assigned to an index number by default. There are two ways to create indexed arrays where the index can be assigned automatically (index always starts at 0),like this:

 

Type 1:$season=array(“summer”,”winter”,”spring”,”autumn”);

 

Type 2:$season[0]=”summer”;

$season[1]=”winter”;

$season[2]=”spring”;

$season[3]=”autumn”;

 

PHP Indexed Arrays Examples:

 

Example 1:

 

<?php

$cars = array(“Volvo”, “BMW”, “Toyota”);

echo “I like ” . $cars[0] . “, ” . $cars[1] . ” and ” . $cars[2] . “.”; ?>

 

Example 2:

    <?php

$size[0]=”Big”;

$size[1]=”Medium”;

$size[2]=”Short”;

echo “Size: $size[0], $size[1] and $size[2]”; ?>

 

PHP Associative Array: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 we can establish a strong association between key and values.There are two ways to create an associative array:

 

$age = array(“Peter”=>”35”, “Ben”=>”37”, “Joe”=>”43”);

(Or)

$age[‘Peter’] = “35”;

$age[‘Ben’] = “37”;

$age[‘Joe’] = “43”;

 

Example of PHP Associative Arrays

 

<?php      /* First method to associate create array. */

$salaries = array(“Kumar” => 2000, “Bala” => 1000, “Sudharsan” => 500);

echo “Salary of Kumar is “. $salaries[‘Kumar’] . “<br />”; echo “Salary of Bala is “. $salaries[‘Bala’]. “<br />”;

echo “Salary of Sudharsan is “. $salaries[‘Sudharsan’]. “<br />”;

/* Second method to create array. */

$salaries[‘Kumar’] = “high”;

$salaries[‘Bala’] = “medium”;

$salaries[‘Sudharsan’] = “low”;

echo “Salary of Kumar is “. $salaries[‘Kumar’] . “<br />”;

echo “Salary of Bala is “. $salaries[‘Bala’]. “<br />”;

echo “Salary of Sudharsan is “. $salaries[‘Sudharsan’]. “<br />”; ?>

    Output

 

Salary of Kumar is 2000

Salary of Bala is 1000

Salary of Sudharsan is 500

Salary of Kumar is high

Salary of Bala is medium

Salary of Sudharsan is low

 

PHP Multidimensional Arrays:PHP multidimensional array is otherwise known as array of arrays. It allows the user to store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is represented by row * column.

 

Multidimensional array Example:

 

$emp = array

(

array(1,“sachin”,400000),

array(2,”john”,500000),

array(3,”rahul”,300000)

);

A simple example of PHP multidimensional array is given below:

Example of PHP Multidimensional Array:

<?php

$marks = array(

“Sachin” => array (

“physics” => 35,

“maths” => 30,

“chemistry” => 39

),

“Raju” => array (

“physics” => 30,

“maths” => 32,

“chemistry” => 29

),

“Venkat” => array (

“physics” => 31,

“maths” => 22,

“chemistry” => 39

)

);

/* Accessing multi-dimensional array values */

echo “Marks for Sachin in physics : ” ;

Echo $marks[‘Sachin’][‘physics’] . “<br />”;

echo “Marks for Raju in maths : “;

echo $marks[‘Raju’][‘maths’] . “<br />”;

echo “Marks for Venkat in chemistry : ” ;

echo $marks[‘Venkat’][‘chemistry’] . “<br />”;?>

   Output for Multidimensional Arrays:

 

Marks for Sachin in physics : 35

Marks for Raju in maths : 32

Marks for Venkat in chemistry : 39

 

Advantages of PHP Array

 

Lesser amount of Code:There is no need to define multiple variables.

 

Easy to traverse: By the help of single loop, we can traverse all the elements of an array easily and quickly.

 

Sorting: We can sort the elements of array easily.

  Previous module has discussed the deployment of PHP programs in XAMPP/ WAMPP server. PHP scripts can be easily written using the syntax, operators, statements, functions, strings and arrays discussed in this module and deployed in XAMPP/ WAMPP server for the successful execution of web pages.

 

Summary

 

This module is intended to discuss about the various operators available in PHP along with the strings applicable in this script. Also, the various types of conditional statements have been discussed with examples. Usage of PHP Arrays and Functions with various types applicable on it has been visited with suitable examples for successful creation and deployment of web pages in web server.

 

Web Links