Unit -II PPT to PDF
Unit -II PPT to PDF
// Output: 1 2 3 4 5
?>
For Loop
• The for loop, is also the most powerful, as it combines the abilities to set up
variables as you enter the loop, test for conditions while iterating loops, and
modify variables after each iteration.
• It is often used when you know in advance how many times you want to
execute the code.
• Syntax:
for (initialization; condition; increment/decrement) {
// Code to be executed in each iteration
}
For Loop
• initialization: This part is executed once before the loop starts. It's typically
used to initialize a loop control variable.
• condition: This is the condition that is evaluated before each iteration of the
loop. If the condition evaluates to true, the loop continues. If it evaluates to
false, the loop terminates.
• increment/decrement: This part is executed after each iteration of the loop.
It's used to increment or decrement the loop control variable.
• Code block: This is the block of code that will be executed repeatedly as
long as the condition remains true.
• It can contain one or more PHP statements enclosed within curly braces
{}.
For Loop
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
// Output: 1 2 3 4 5
?>
For Loop
• Let us compare when to use for and while loops.
• The for loop is explicitly designed around a single value that changes
regularly.
• Usually, you have a value that increments, as when you are passed a list of
user choices and want to process each choice in turn.
• But you can transform the variable anyway you like
Use of Comma in For Loop
for ($i = 1, $j = 1 ; $i + $j < 10 ; $i++ , $j++)
{
// ...
}
Explanation
• $i = 1, $j = 1 // Initialize $i and $j
• $i + $j < 10 // Terminating condition
• $i++ , $j++ // Modify $i and $j at the end of each iteration
The Do… While Loop
• A slight variation to the while loop is the do ... while loop, used when you
want a block of code to be executed at least once and made conditional only
after that.
• The do-while loop in PHP is similar to the while loop, but with one key
difference.
• The do-while loop will always execute the code block at least once,
regardless of whether the condition is true or false.
• After the first iteration, it will continue to execute the block of code as long
as the specified condition evaluates to true.
The Do… While Loop
• Syntax:
do {
// Code to be executed
} while (condition);
Code block: This is the block of code that will be executed repeatedly. It
contains one or more PHP statements enclosed within curly braces {}.
condition: This is the condition that is evaluated after each iteration of the
loop. If the condition evaluates to true, the loop continues. If it evaluates to
false, the loop terminates.
The Do… While Loop
<?php
$i = 1; // Initialize a counter variable
do {
echo $i . " "; // Output the current value of $i
$i++; // Increment the counter variable
} while ($i <= 5);
// Output: 1 2 3 4 5
?>
The Beak Statement
• The break statement is used to come out of the loop.
• The break statement in PHP is used to immediately terminate the execution
of a loop.
• When the break statement is encountered within a loop, the program exits
the loop and continues executing the code after the loop.
• It is commonly used to prematurely exit a loop based on a certain
condition.
• The break statement can be used with for, while or do-while
• It is also used with a switch statement
The Beak Statement Example
<?php
for ($i = 0; $i < 10; $i++) {
echo $i . " "; // Output the current value of $i
if ($i == 5) {
break; // Terminate the loop when $i equals 5
}
}
// Output: 0 1 2 3 4 5
?>
The Continue Statement
• The continue statement is a little like a break statement, except that it
instructs PHP to stop processing the current loop and to move right to its
next iteration.
• So, instead of breaking out of the whole loop, PHP exits only the current
iteration
<?php
$j = 10;
while ($j > −10) { • For all values of $j between 10 and −10, except 0, the
result of calculating 10 divided by $j is displayed.
$j--; • But for the particular case of $j is 0, the continue
statement is issued and execution skips immediately to
if ($j == 0) continue; the next iteration of the loop.
echo (10 / $j) . "<br>";}
?>
Arrays
• An array can hold multiple, separate pieces of information. An array is
therefore like a list of values, each value being a string, a number or
even another array.
• Arrays are structured as a series of key value pairs, where one pair is an
item or element of that array.
• For each item in the list, there is a key (or index) associated with it.
• PHP supports two kinds of arrays: indexed, which use numbers as the
keys and associative, which use strings as keys
• As in most programming languages, with indexed arrays, arrays will
begin with the first index at 0, unless you specify the keys explicitly.
• An array follows the same naming rules as any other variable.
Arrays
• For example, an HTML parser such as those used by a search engine could place all the
elements of a web page into an associative array whose names reflect the page’s
structure:
$html['title'] = "My web page";
$html['body'] = "... body of web page ...";
• The program would also probably break down all the links found within a page into
another array, and all the headings and subheadings into another.
• When you use associative rather than numeric arrays, the code to refer to all of these
items is easy to write and debug
Assignment Using the array Keyword
• So far, you’ve seen how to assign values to arrays by just adding new items
one at a time.
• Whether you specify keys, specify numeric identifiers, or let PHP assign
numeric identifiers implicitly, this is a long-winded approach.
• A more compact and faster assignment method uses the array keyword.
Assignment Using the array Keyword
<?php
$p1 = array("Copier", "Inkjet", "Laser", "Photo");
echo "p1 element: " . $p1[2] . "<br>";
$p2 = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
echo "p2 element: " . $p2['inkjet'] . "<br>";
?>
The first half of this snippet assigns the old, shortened product descriptions
to the array $p1.
There are four items, so they will occupy slots 0 through 3. Therefore, the
echo statement prints p1 element: Laser
Assignment Using the array Keyword
<?php
$p2 = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
echo "p2 element: " . $p2['inkjet'] . "<br>";
?>
• The second half assigns associative identifiers and accompanying longer
product descriptions to the array $p2 using the format index => value.
• The use of => is similar to the regular = assignment operator, except that
you are assigning a value to an index and not to a variable.
• The index is then inextricably linked with that value, unless it is assigned a
new value.
• The echo command prints: p2 element: Inkjet Printer
Assignment Using the array Keyword
<?php
$p1 = array("Copier", "Inkjet", "Laser", "Photo");
echo "p1 element: " . $p1[2] . "<br>";
$p2 = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
echo "p2 element: " . $p2['inkjet'] . "<br>";
?>
Undefined offset error, as the array identifier for each is incorrect:
echo $p1['inkjet']; // Undefined index
echo $p2[3]; // Undefined offset
For Each Loop
• The creators of PHP have gone to great lengths to make the language easy
to use.
• So, not content with the loop structures already provided, they added
another one especially for arrays: the foreach ... as loop.
• Using it, you can step through all the items in an array, one at a time, and
do something with them.
• The process starts with the first item and ends with the last one, so you
don’t even have to know how many items there are in an array.
For Each Loop
<?php
$paper = array("Copier", "Inkjet", "Laser", "Photo");
$j = 1;
foreach($paper as $item)
{
echo "$j: $item<br>";
++$j;
}
?>
For Each Loop
<?php
$paper = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
foreach($paper as $item => $description)
echo “<strong>$item: </strong> $description<br>";
?>
For Each Loop
• Remember that associative arrays do not require numeric indexes, so the
variable $j is not used in this example.
• Instead, each item of the array $paper is fed into the key/value
• pair of variables $item and $description, from which they are printed out.
foreach($paper as $item => $description)
echo “<strong>$item: </strong> $description<br>";
For Each Loop
As an alternative syntax to foreach ... as, you can use the list function in
conjunction with the each function
<?php
$paper = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
while (list($item, $description) = each($paper))
echo "$item: $description<br>";
?>
Multidimensional Arrays
• A simple design feature in PHP’s array syntax makes it possible to create
arrays of more than one dimension.
• In fact, they can be as many dimensions as you like (although it’s a rare
application that goes further than three).
• That feature makes it possible to include an entire array as a part of
another one.
• Run Multi_Dim Project and explain
Multidimensional Arrays
<?php echo "<pre>";
$chessboard = array( foreach($chessboard as $row)
array('r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'), {
array('p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'), foreach ($row as $piece)
array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '), echo "$piece ";
array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '), echo "<br>";
array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '), }
array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '), echo "</pre>";
array('P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'), ?>
array('R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R')
);
Array Functions
• is_array
• count
• sort
• shuffle
• explode
• implode
• extract
• compact
• reset
• end
is_array()
Arrays and variables share the same namespace.
This means that you cannot have a string variable called $fred and an array
also called $fred.
If you want to ccheck whether a variable is an array, you can use the is_array
function
like this:
echo (is_array($fred)) ? "Is an array" : "Is not an array";
Note that if $fred has not yet been assigned a value, an Undefined variable
message will be generated.
If $fred is an array, it will display the message Is an array. If $fred is not an
array Is not an array will be displayed
count()
• Sometimes you need to know exactly how many elements
• there are in your array, particularly if you will be referencing them
directly. To count all the elements in the top level of an array, use a
command such as the following:
echo count($fred);
If wish to know how many elements there are altogether in a
multidimensional array, you can use a statement such as:
echo count($fred, 1);
The second parameter is optional and sets the mode to use. It should be
either a 0 to limit counting to only the top level, or 1 to force recursive
counting of all subarray elements too.
sort()
• Sorting is so common that PHP provides a built-in function. In its
simplest form, you would use it like this:
sort($fred);
• Unlike some other functions, sort will act directly on the supplied array
rather than returning a new array of sorted elements.
• Instead, it returns TRUE on success and FALSE on error and also supports
a few flags, but the main two that you might wish to use force sorting to
be made either numerically or as strings, like this:
sort($fred, SORT_NUMERIC);
sort($fred, SORT_STRING);
• You can also sort an array in reverse order using the rsort function.
rsort($fred, SORT_NUMERIC);
rsort($fred, SORT_STRING);
shuffle()
• There may be times when you need the elements of an array to be put in
random order, such as when you’re creating a game of playing cards:
shuffle($cards);
• Like sort, shuffle acts directly on the supplied array and returns TRUE on
success or FALSE on error.
• Some of the real-life examples include
• Randomizing Quiz Questions
• Shuffling Playlists
• Randomizing Displayed Ads
• Randomizing Product Recommendations
• Randomizing Card Dealing in Games
• Randomizing Test Cases in Software Testing
explode()
• This is a very useful function with which you can take a string containing
several items separated by a single character (or string of characters) and
then place each of these items into an array.
• One handy example is to split up a sentence into an array containing all its
words
Example
<?php
$temp = explode(' ', "This is a sentence with seven words");
print_r($temp);
?>
explode()
• This is a very useful function with which you can take a string containing
several items separated by a single character (or string of characters) and
then place each of these items into an array.
• One handy example is to split up a sentence into an array containing all its
words
Example
<?php
$temp = explode(' ', "This is a sentence with seven words");
print_r($temp);
?>
explode()
The first parameter, the delimiter, need not be a space or even a single character
The following shows a slight variation.
Array_Eg
Dummy_proj