You are on page 1of 31

 Chapter -2

Control Statement and Array


CONDITIONALS AND LOOPS
 Control Structures, Blocks, and Compound
Statements
The flow of your program in three ways:
• Execute a sequence of statements.
• Based on a test, branch to an alternative sequence of
statements.
• Repeat a sequence of statements until some condition
is met.
 The decision-making constructs (if, if/else, if/else if)
contain a control expression that determines whether a
block of statements will be executed.
 The looping constructs (while, for) allow the program
to repetitively execute a statement block until some
condition is satisfied.
Conditionals
Format
o if (condition){
statements; }
Example:
if ( $age > 21 ){ print "Let's Party!"; }
 if (condition){ statements1; }
else{ statements2; }
Example:
if ( $x > $y ){ print "$x is larger"; }
else{
print "y is larger"; }
if (condition) { statements1; }
elseif (condition) { statements2; }
elseif (condition) { statements3; }
else{ statements4; }
 The switch Statement
Example:
$color=“blue”;
switch ($color)
{
case "red":
print "Hot!";
break;
case "blue":
print "Cold.";
break;
default:
print "Not a good choice.";
break;
}
Loops
 Loops are used to execute a segment of code
repeatedly until some condition is met
 PHP‟s basic looping constructs are the following:
• while
• for
• foreach
• do/while
The while Loop
 Format
 while (condition) { statements;
increment/decrement counter; }
The do/while Loop
 Format
do { statements; }
while (condition);
<html>
<head>
<title>Looping Constructs</title><body
bgcolor='f0f8ff„><h3>Do... While Loop</h3>
<font face='arial' size='+1'>
<?php
$i=10;
do{
echo "$i ";
$i--;
}while ( $i > 0 );
?></body></html>
The for Loop
Format
 for(Expression1;Expression2;Expression3) {
statement(s);}
 for (initialize;test; increment/decrement) {
statement(s);}
The foreach Loop
 The foreach loop is designed to work with arrays and works
only with array.
Format
$array_name=array( item1, item2, item3, ...);
foreach ($array_name as $value)
{
do-something with the element's value;
}
Example:
$suit=array("diamond", "spade", "club", "heart");
foreach ( $suit as $card_type)
{
echo $card_type . "<br />";
}
PHP OPERATORS AND EXPRESSIONS
 When you terminate an expression with a semicolon, you have a
complete statement; for example, n = 5 + 4;
 Expression
Sum = 5 + 4
new value operator operand operator operand
In the numeric expression 5 + 4 - 2, three numbers are combined.
The operands for the + sign are 5 and 4
Assignment
 An assignment statement evaluates the expression on the right side
of the equal sign and assigns the result to the variable on the left
side of the equal sign.
 The equal sign is the assignment operator.
 $total = 5 + 4;
 $name = "Tony";
Arithmetic Operators
 Arithmetic operators take numerical values (either literals or
variables) as their operands and return a single numerical value.
 The standard arithmetic operators are addition (+), subtraction (-),
multiplication (*), and division (/).
Table 5.2. Arithmetic Operators
Operator/Operands Function
x+y Addition
x–
y Subtraction
x*
y Multiplicati
on
x/y Division
x%y Modulus
Short Circuit Assignment Operators
 The short circuit assignment operators allow you to perform an
arithmetic or string operation by combining an assignment operator
with an arithmetic or string operator.
 For example, $x = $x + 1 can be written $x+=1.
Table 5.3. Assignment Operators
Operator Example Meaning
= $x = 5; Assign 5 to variable $x.
+= $x += 3; Add 3 to $x and assign result to $x.
-= $x -= 2;
Subtract 2 from $x and assign result to $x.
*= $x *= 4; Multiply $x by 4 and assign result to
$x.
/= $x /= 2; Divide $x by 2 and assign result to $x.
%= $x %= 2; Divide $x by 2 and assign remainder to $x.
Autoincrement and Autodecrement Operators
 To make programs easier to read, to simplify typing, and, at
the machine level, to produce more efficient code, the
autoincrement (++) and autodecrement (--) operators are
provided.
 The autoincrement operator performs the simple task of
incrementing the value of its operand by 1, and the auto
decrement operator decrements the value of its operand
by 1.
The operator has two forms:
 The first form prefixes the variable with either ++ or --
(e.g., ++$x or --$x);
 the second form postfixes (places the operator after) the
variable name with either ++ or -- (e.g., $x++, x--).
Table 5.4. Auto increment and Auto decrement
Operators
Operator Function What It Does Example
 ++$x Preincrement Adds 1 to $x $x = 3;
$x++; $x is now 4
 $x++ Postincrement Adds 1 to $x $x = 3;
++$x; $x is now 4
 ––$x Predecrement Subtracts 1 from $x $x = 3;
$x; –– $x is now 2
 $x–– Postdecrement Subtracts 1 from $x $x = 3;
 --$x; $x is now 2
 The Autoincrement/Autodecrement and
Assignment
 The placement of the operators does make a
difference in more complex expressions especially
when part of an assignment; for example, $y =
$x++ is not the same as $y = ++$x. See Figure
5.5.Figure 5.5. Start with: $y = 0; $x = 5; See Example 5.5.
Casting Operators
 As defined earlier, PHP is a loosely typed language, which really means that
you don‟t have to be concerned about what kind of data is stored in a
variable.
 You can assign a number to $x on one line and on the next line assign a
string to $x; you can compare numbers and strings, strings and booleans,
and so on.
 PHP automatically converts values when it assigns values to a variable or
evaluates an expression
Table 5.6. Casting Operators
Operator Synonym Changes Data Type To
 (int) (integer) Integer
 (float) (real) Floating point
 (string) String
 (bool) (boolean) Boolean
Format
variable = (cast operator) value;
Example:
 $salary = "52000"; // Variable is assigned a string value
 $salary = (float)$salary; // Value is forced to float and reassigned
Comparison Operators
 When operands are compared, relational and equality operators are
used. The operands can be numbers or strings.
 The result of the comparison is either true or false, a Boolean value.
 Comparisons are based on the type of the operands being compared.
 If, for example, two numbers are compared, the comparison is
numeric, such as 5 > 4.
Table 5.7. Comparison Operators
Operator/Operands Function
$x == $y $x is equal to $y
$x != $y $x is not equal to $y
$x > $y $x is greater than $y
$x >= $y $x is greater than or equal to $y
$x < $y $x is less than $y
$x <= $y $x is less than or equal to $y
$x === $y $x is identical to $y in value
and type
$x !== $y $x is not identical to $y
Logical Operators
Logical operators let you test combinations of
expressions resulting in Boolean value, true and false.
See Table 5.10.
Table 5.10. Testing Expressions with Logical
Operators
Example Name Result
 $a && $b And
TRUE if both $a and $b are TRUE.
 $a || $b Or
TRUE if either $a or $b is TRUE.
 $a and $b And
TRUE if both $a and $b are TRUE.
Table 5.10. Testing Expressions with Logical Operators
Example Name Result
$a xor $b Xor
TRUE if either $a or $b is TRUE, but not both.
! $a Not TRUE if $a is not TRUE.
The Conditional Operator
 The conditional operator is called a ternary operator because it requires
three operands. It is often used as a shorthand method for if/else
conditional statements
Format
conditional expression ? expression : expression
Examples:
 $x ? $y : $z
If $x evaluates to true, the value of the expression beco
mes $y, else the value of the expression becomes $z.
 $big = ($x >$y)?$x :$y
If x is greater than $y, $x is assigned to variable
$big, else $y is assigned to variable $big.
ARRAYS
 What Is an Array?
Figure 8.2. A numeric array indexed by number, and an
associative array indexed by string.
Although PHP internally treats both numeric and associative arrays in the
same way, there are two ways to visualize an array: an array indexed by a
number and an array indexed by a string
Let‟s look at Example 8.1, which shows a numeric array, an array indexed by
number.
<html>
<head><title>Array of Products</title></head>
<body bgcolor="lightgreen">
<?php
$products=array('floral talc','body mist', 'perfumed powder', 'bath gel');
echo "<b>\$products is $products.<br />\n";
echo "\$products[0] is $products[0].<br />\n";
echo "\$products[1] is $products[1].<br />\n";
echo "\$products[2] is $products[2].<br />\n";
echo "\$products[3] is $products[3].<br />\n";
?>
<br /><em>Let's add another element to the array.</em><br />
$products[]='gentle soap';<br />
<?php
$products[]='gentle soap';
echo "\$products[4] is $products[4].<br />\n";
?>
</body>
</html>
Now let‟s look at Example 8.2, which shows an
associative array, an array indexed by a string.
<?php
$show=array( 'Title'=>'Aga-Boom','Author'=> 'Dmitri
Bogatirev','Genre'=> 'Physical comedy',);
echo "\$show is $show.<br />\n";
?>
$show['Title'] is <?=$show['Title']?>.<br />
$show['Author'] is <?=$show['Author']?>.<br />
$show['Genre'] is <?=$show['Genre']?>.<br />
Creating and Naming an Array
Table 8.1. Functions to Create an Array
Function What It Does
 array()
Creates an array
 array_combine()

Creates an array by using one array for keys and anot


her for its values.

Table 8.1. Functions to Create an Array


Function
 array_fill()
Fills an array with values
 array_pad()
Pads an array to the specified length with a value
 compact() Creates array containing variables and their values
 range() Creates an array containing a range of elements
Table 8.2. Functions to Check for Existence of an Array

 Function What It Does


 array_key_exists()
Checks if the given key or index exis
ts in the array
 in_array()
Checks if a value exists in an array
 is_array()
Checks if the variable is an array; re
turns TRUE or FALSE
Function
 array_count_values()
Returns an array consisting of the values of a
n array and the number of times each value
occurs in an array
 count()
Returns the number of elements in an array
or properties of an object
 sizeof()
Returns the size of the array, same as coun
t()
 Table 8.6. Sorting an Array
 array_multisort()
Sorts multiple or multidimensional arrays
 arsort()
Sorts an array in reverse order and maintains
index association
 asort()
Sorts an array and maintains index association
 krsort()
Sorts an array by key in reverse order
 ksort()
Sorts an array by key
 rsort() Sorts an array in reverse order
 sort() Sorts an array
 uasort() Sorts an array with a user--
‐defined comparison function and maintains
index association
USER-DEFINED FUNCTIONS
 What Is a Function?
 Functions are self-contained units of a program
designed to accomplish a specified task such as
calculating a mortgage payment, retrieving data
from a database, or checking for valid input.
 Passing Arguments
 What Are Arguments and Parameters?
Passing by Value
 When you pass arguments by value, PHP makes
a copy of the variable, so that if you change it in
the function, you are only changing the copy
Passing by Reference
 When passing a variable by reference (only
variables can be passed by reference), the value
being passed can be changed directly, because
instead of passing a copy of the value, you are
passing a reference to the orginial variable.
 Return Values
The require() and include() Constructs
 PHP provides the require() and include() constructs to
allow you to use the functions from the library file in a
 PHP script as shown here:

Format
 <?php

require("mylibrary.php"); // Now functions in the library


can be called
echo "The average is ", ave(array(11,3,5,7,34));
 ?>
End !!!!

You might also like