0% found this document useful (0 votes)
39 views42 pages

PHP Chapter 3 ١

Uploaded by

taj200153
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views42 pages

PHP Chapter 3 ١

Uploaded by

taj200153
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Web Applications

Development
ITSE 3302
‫تطوير تطبيقات الشبكة العالمية‬
Dr. Moamar Elyazgi
Section 2 - PHP Language

Chapter 3
PHP

Operator Types, Decision Making, Loop Types


and Arrays
3.1 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:

 Let’s have a look on all operators one by one. 3


3.1.1 Arithmetic Operators
• The following arithmetic operators are supported by PHP language:

4
3.1.1 Arithmetic Operators - Example
<html> $c = $a / $b;
<head><title>Arithmetical echo "Division Operation Result: $c <br/>";
Operators</title><head> $c = $a % $b;
echo "Modulus Operation Result: $c <br/>";
<body>
$c = $a++;
<?php echo "Increment Operation Result: $c <br/>";
$a = 42; $c = $a--;
$b = 20; echo "Decrement Operation Result: $c <br/>";
$c = $a + $b; ?>
echo "Addition Operation Result: $c <br/>"; </body>
$c = $a - $b; </html>
Addition Operation Result: 62
echo "Subtraction Operation Result: $c <br/>"; Subtraction Operation Result: 22
$c = $a * $b; Multiplication Operation Result: 840
echo "Multiplication Operation Result: $c Division Operation Result: 2.1
<br/>"; Modulus Operation Result: 2
Increment Operation Result: 42
This will produce the following result:
Decrement Operation Result: 43 5
3.1.2 Comparison Operators
There are following comparison operators supported by PHP language.

6
3.1.2 Comparison Operators - Example
<?php<html> }else{ }else{
<head><title>Comparison echo "TEST2 : a is not greater than echo "TEST5 : a is neither greater than
Operators</title><head> b<br/>"; nor equal to b<br/>";
}
<body> }
if( $a < $b ){ if( $a <= $b ){
<?php
echo "TEST3 : a is less than b<br/>"; echo "TEST6 : a is either less than or
$a = 42; equal to b<br/>";
$b = 20; }else{
echo "TEST3 : a is not less than }else{
if( $a == $b ){ echo "TEST6 : a is neither less than nor
b<br/>";
echo "TEST1 : a is equal to } equal to b<br/>";
b<br/>"; if( $a != $b ){ }
}else{ echo "TEST4 : a is not equal to ?>
echo "TEST1 : a is not equal to b<br/>"; </body>
</html>
b<br/>"; }else{
} echo "TEST4 : a is equal to b<br/>"; TEST1 : a is not equal to b
if( $a > $b ){ } TEST2 : a is greater than b

echo "TEST2 : a is greater than if( $a >= $b ){ TEST3 : a is not less than b
TEST4 : a is not equal to b
echo "TEST5 : a is either greater than
b<br/>"; TEST5 : a is either greater than or
or equal to b<br/>"; equal to b 7
3.1.3 Logical Operators
• The following logical operators are supported by PHP language.

8
3.1.3 Logical Operators - Example
<html> if( $a || $b ){ This will produce
<head><title>Logical echo "TEST3 : Either a or b is echo "TEST5 : a is true <br/>"; the following
Operators</title><head> true<br/>"; }else{ result:
<body> }else{ echo "TEST5 : a is false<br/>";
} TEST1 : Either a or b
<?php echo "TEST3 : Both a and b are if( $b ){
$a = 42; false<br/>"; echo "TEST6 : b is true <br/>"; is false
$b = 0; } }else{
if( $a && $b ){ if( $a or $b ){ echo "TEST6 : b is false<br/>"; TEST2 : Either a or b
echo "TEST1 : Both a and b are echo "TEST4 : Either a or b is }
if( !$a ){ is false
true<br/>"; true<br/>";
echo "TEST7 : a is true <br/>";
}else{ }else{ TEST3 : Either a or b
}else{
echo "TEST1 : Either a or b is echo "TEST4 : Both a and b are echo "TEST7 : a is false<br/>"; is true
false<br/>"; false<br/>"; }
} } if( !$b ){ TEST4 : Either a or b
if( $a and $b ){ $a = 10; echo "TEST8 : b is true <br/>";
}else{ is true
echo "TEST2 : Both a and b are $b = 20;
echo "TEST8 : b is false<br/>";
true<br/>"; if( $a ){ TEST5 : a is true
}
}else{ } ?> TEST6 : b is true
echo "TEST2 : Either a or b is $a = 10; </body>
false<br/>"; $b = 20; </html> TEST7 : a is false
} if( $a ){ TEST8 : b is false
9
3.1.4 Assignment Operators
• PHP supports the following assignment
operators:

10
3.1.4 Assignment Operators
<html>
<head><title>Assignment Operators</title><head>
<body>
This will produce the following result:
<?php
$a = 42;
$b = 20;
Addition Operation Result: 62
$c = $a + $b; /* Assignment operator */
echo "Addition Operation Result: $c <br/>"; Add AND Assignment Operation Result: 104
$c += $a; /* c value was 42 + 20 = 62 */ Subtract AND Assignment Operation Result: 62
echo "Add AND Assignment Operation Result: $c <br/>"; Multiply AND Assignment Operation Result: 2604
$c -= $a; /* c value was 42 + 20 + 42 = 104 */ Division AND Assignment Operation Result: 62
echo "Subtract AND Assignment Operation Result: $c <br/>"; Modulus AND Assignment Operation Result: 20
$c *= $a; /* c value was 104 - 42 = 62 */
echo "Multiply AND Assignment Operation Result: $c <br/>";
$c /= $a; /* c value was 62 * 42 = 2604 */
echo "Division AND Assignment Operation Result: $c <br/>";
$c %= $a; /* c value was 2604/42 = 62*/
echo "Modulus AND Assignment Operation Result: $c <br/>";
?>
</body>
</html>} 11
3.1.5 Conditional Operator
• There is one more operator called the conditional operator. It first
evaluates an expression for a true or false value and then executes
one of the two given statements depending upon the result of the
evaluation.

$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true
12
3.2 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. 13
3.2 Precedence of PHP Operators

14
3.3 PHP ─ 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 the following three decision making statements:
• 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 several condition are 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
15
long blocks of if..elseif..else code.
3.3.1 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.
<html>
• Syntax <body>
if (condition) <?php
code to be executed if condition is true; $d=date("D");
else if ($d=="Fri")
code to be executed if condition is false; echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
16
3.3.2 The elseIf Statement
• If you want to execute some code if one of the several conditions is true, then use the
elseif statement.
<html>
Syntax <body>
if (condition) <?php
code to be executed if condition is true; $d=date("D");
if ($d=="Fri")
elseif (condition) echo "Have a nice weekend!";
code to be executed if condition is true; elseif ($d=="Sun")
else echo "Have a nice Sunday!";
code to be executed if condition is false; else
echo "Have a nice day!";
?>
</body>
</html>
17
3.3.3 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; } 18
3.3.3 The Switch Statement
<html> break; echo "Wonder which day is
<body> case "Thu": this ?";
<?php echo "Today is Thursday"; }
$d=date("D"); break; ?>
switch ($d) case "Fri": </body>
{ echo "Today is Friday"; </html>
case "Mon": break;
echo "Today is Monday"; case "Sat": The Answer is
break; echo "Today is Saturday"; today day
case "Tue": break;
case "Sun":
echo "Today is Tuesday";
echo "Today is Sunday";
break;
break;
case "Wed":
default:
echo "Today is Wednesday"; 19
3.4 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. 20
3.4.1 The for loop statement
• The for statement is used when you <html>
know how many times you want to <body>
<?php
execute a statement or a block of $a = 0;
statements. $b = 0;
for( $i=0; $i<5; $i++ )
• Syntax {
$a += 10;
for (initialization; condition; increment)
{ $b += 5;
}
code to be executed; echo ("At the end of the loop a=$a and b=$b" );
} ?>
</body>
This will produce the following result: </html>
At the end of the loop a=50 and b=25 21
3.4.2 The while loop statement
• The while statement will execute a block <html>
of code if and as long as a test expression <body>
<?php
is true.
$i = 0;
• If the test expression is true, then the code $num = 50;
while( $i < 10)
block will be executed. After the code has {
executed the test expression will again be $num--;
evaluated and the loop will continue until $i++;
}
the test expression is found to be false.
echo ("Loop stopped at i = $i and num = $num"
• Syntax );
The result: ?>
while (condition) is </body>
{ </html>
code to be executed; 22
} Loop stopped at i = 10 and num = 40
3.4.3 The do...while loop statement
• The do...while statement will execute a <html>
block of code at least once - it will <body>
then repeat the loop as long as a <?php
condition is true. $i = 0;
$num = 0;
• Syntax do
do {
{ $i++;
}while( $i < 10 );
code to be executed; The result: echo ("Loop stopped at i = $i" );
} is
?>
while (condition); </body>
</html>
Loop stopped at i = 10
23
3.4.4 The foreach loop statement
• The foreach statement is used to loop <html>
through arrays. For each pass the value <body>
<?php
of the current array element is assigned
$array = array( 1, 2, 3, 4, 5);
to $value and the array pointer is foreach( $array as $value )
moved by one and in the next pass next {
element will be processed. The result: echo "Value is $value <br />";
}
is
• Syntax ?>
</body>
foreach (array as value) </html>
{ Value is 1
code to be executed; Value is 2
} Value is 3
Value is 4 24
Value is 5
3.6 The continue statement
• The PHP continue keyword is used to
<html>
halt the current iteration of a loop but it <body>
does not terminate the loop. <?php
$array = array( 1, 2, 3, 4, 5); The result:
• Just like the break statement the foreach( $array as $value ) is
continue statement is situated inside {
if( $value == 3 )continue;
the statement block containing the echo "Value is $value <br />";
code that the loop executes, preceded } Value is 1
?> Value is 2
by a conditional test. </body> Value is 4
</html> Value is 5
• For the pass encountering continue
statement, rest of the loop code is
skipped and next pass starts. 25
3.7 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,
it is easy to define an array of 100 length.
• There are three different kind of arrays and each array value is accessed using an ID
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 26
accessed using multiple
3.7.1 Numeric Array
<html> foreach( $numbers as $value )
• These arrays can store
<body> {
numbers, strings and echo "Value is $value <br />";
<?php
any object but their /* First method to create array. */ }
The result:
index will be $numbers = array( 1, 2, 3, 4, 5); ?> is
represented by foreach( $numbers as $value ) </body>
{ </html>
numbers.
echo "Value is $value <br />";
• By default, the array } Value is 1
/* Second method to create array. Value is 2
index starts from zero. Value is 3
*/
Value is 4
• Here we have used $numbers[0] = "one"; Value is 5
array() function to $numbers[1] = "two"; Value is one
$numbers[2] = "three"; Value is two
create array. This
$numbers[3] = "four"; Value is three
function is explained $numbers[4] = "five"; Value is four
in function reference. Value is five 27
3.7.2 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.
28
3.7.2 Associative Arrays
<html> echo "Salary of zara is ". $salaries['zara']. "<br
<body> />";
<?php /* Second method to create array. */
/* First method to associate create array. $salaries['mohammad'] = "high";
*/ $salaries['qadir'] = "medium";
$salaries = array( $salaries['zara'] = "low";
"mohammad" => 2000, echo "Salary of mohammad is ".
"qadir" => 1000, $salaries['mohammad'] . "<br />";
"zara" => 500 echo "Salary of qadir is ". $salaries['qadir'].
); "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br
echo "Salary of mohammad is ".
/>";
$salaries['mohammad'] . "<br />";
?>
echo "Salary of qadir is ". $salaries['qadir'].
</body>
"<br />"; </html>
29
3.7.2 Associative Arrays

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

30
3.7.3 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.
• PHP supports multidimensional arrays that are two, three, four, five, or more
levels deep. However, arrays more than three levels deep are hard to manage
for most people.
• The dimension of an array indicates the number of indices you need to select an
element.
For a two-dimensional array you need two indices to select an element
For a three-dimensional array you need three indices to select an element 31
3.7.3 Multidimensional Arrays
"zara" => array
<html>
(
<body>
"physics" => 31,
<?php
"maths" => 22,
$marks = array(
"chemistry" => 39
"mohammad" => array
)
(
);
"physics" => 35,
/* Accessing multi-dimensional array values */
"maths" => 30,
echo "Marks for mohammad in physics : " ;
"chemistry" => 39
echo $marks['mohammad']['physics'] . "<br />";
),
echo "Marks for qadir in maths : "; The result:
"qadir" => array
echo $marks['qadir']['maths'] . "<br />"; is
(
echo "Marks for zara in chemistry : " ;
"physics" => 30,
echo $marks['zara']['chemistry'] . "<br />";
"maths" => 32,
?>
"chemistry" => 29 Marks for mohammad in physics : 35
</body> Marks for qadir in maths : 32
),
</html> Marks for zara in chemistry : 39 32
3.8 PHP - Sort Functions For Arrays
• PHP has several functions that deal with sorting arrays, and this document exists to help
sort it all out.
• The main differences are:
• Some sort based on the array keys, whereas others by the values: $array['key'] = 'value';
• Whether or not the correlation between the keys and values are maintained after the sort,
which may mean the keys are reset numerically (0,1,2 ...)
• The order of the sort: alphabetical, low to high (ascending), high to low (descending),
numerical, natural, random, or user defined
• Note: All of these sort functions act directly on the array variable itself, as opposed to
returning a new sorted array
• If any of these sort functions evaluates two members as equal then the order is undefined33
(the sorting is not stable).
3.8 PHP - Sort Functions For Arrays
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order, according to the
value
• ksort() - sort associative arrays in ascending order, according to the key
• arsort() - sort associative arrays in descending order, according to the
value
• krsort() - sort associative arrays in descending order, according to the
34
key
3.8.1 PHP - sort() Function
The following example sorts the elements of the $cars array in
ascending alphabetical order:
• This function <!DOCTYPE html>
sorts an array. <html> The result:
<body> is
Elements will be <?php
arranged from $cars = array("Volvo", "BMW", "Toyota");
sort($cars);
lowest to highest $clength = count($cars); BMW
Toyota
when this for($x = 0; $x < $clength; $x++)
Volvo
{
function has echo $cars[$x];
completed. echo "<br>";}
?>
</body>
</html> 35
3.8.1 PHP - sort() Function
The following example sorts the elements of the $numbers
array in ascending numerical order:
<!DOCTYPE html> The
<html> result: is
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers); 2
$arrlength = count($numbers); 4
for($x = 0; $x < $arrlength; $x++) { 6
echo $numbers[$x]; 11
echo "<br>"; 22
}
?>
</body>
</html> 36
3.8.2 PHP - rsort() Function
The following example sorts the elements of the $cars array in
descending alphabetical order:
<!DOCTYPE html>
• This function <html>
The result:
sorts an array in <body> is
<?php
reverse order $cars = array("Volvo", "BMW", "Toyota");
(highest to rsort($cars);
$clength = count($cars); Volvo
lowest). Toyota
for($x = 0; $x < $clength; $x++) { BMW
echo $cars[$x];
echo "<br>";
}
?>
</body> 37
</html>
3.8.3 PHP - asort() Function
The following example sorts an associative array in
• This function sorts an ascending order, according to the value:
array such that array <!DOCTYPE html>
indices maintain their <html>
<body>
correlation with the <?php
array elements they are $age = array("Peter"=>"5", "Ben"=>"7", "Joe"=>"3");
associated with. asort($age);

• This is used mainly foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
when sorting associative echo "<br>";
arrays where the actual }
Key=Joe, Value=3
element order is ?> Key=Peter, Value=5
The
</body> result: is
Key=Ben, Value=7
significant. </html> 38
3.8.4 PHP - ksort() Function
The following example sorts an associative array in
• Sorts an array by key, ascending order, according to the key:
maintaining key to data <!DOCTYPE html>
correlations. <html>
<body>
• This is useful mainly for <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
associative arrays. ksort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
Key=Ben, Value=37
?> Key=Joe, Value=43
The
</body> result: is
Key=Peter, Value=35
</html> 39
3.8.5 PHP - arsort() Function
The following example sorts an associative array in
• This function sorts an descending order, according to the value:
array such that array <!DOCTYPE html>
indices maintain their <html>
<body>
correlation with the <?php
array elements they are $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
associated with. arsort($age);

• This is used mainly foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
when sorting associative echo "<br>";
arrays where the actual }
Key=Joe, Value=43
element order is ?> Key=Ben, Value=37
The
</body> result: is
Key=Peter, Value=35
significant. </html> 40
3.8.6 PHP - krsort() Function
The following example sorts an associative array in
descending order, according to the key:
<!DOCTYPE html>
<html>
• Sorts an array by key in <body>
reverse order, <?php
maintaining key to data $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
correlations.
foreach($age as $x => $x_value) {
• This is useful mainly for echo "Key=" . $x . ", Value=" . $x_value;
associative arrays. echo "<br>";
}
Key=Peter, Value=35
?> Key=Joe, Value=43
The
</body> result: is
Key=Ben, Value=37
</html> 41
42

You might also like