0% found this document useful (0 votes)
29 views

Unit -II PPT to PDF

PHP Basics

Uploaded by

Geetha Poornima
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)
29 views

Unit -II PPT to PDF

PHP Basics

Uploaded by

Geetha Poornima
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
You are on page 1/ 86

Unit -II

Conditionals, Loops and Arrays


Conditionals in PHP
• Conditionals alter program flow.
• They enable the user to ask questions about certain things and respond to
the answers you get in different ways.
• Conditionals are very essential to dynamic web pages—the goal of using
PHP in the first place—because they make it easy to create different output
each time a page is viewed.
• There are three types of non-looping conditionals: the if statement, the
switch statement, and the ? operator.
The if statement
• An if statement without an else part allows for conditional execution of
code based solely on whether the condition specified in the if statement
evaluates to true.
• If the condition is true, the code block immediately following the if
statement is executed.
• If the condition is false, the code block is simply skipped, and program
execution continues with the next statement after the if block
Syntax
if (condition) {
// code block to execute if the condition is true
}
The if Statement
Example

if ($bank_balance < 100)


{
$money = 1000;
$bank_balance += $money;
}

int number = 10;


if (number > 5) {
System.out.println("Number is greater than 5");
}
The if … else statement
An if statement with an else part allows for conditional execution of
code based on whether the condition specified in the if statement
evaluates to true or false.
If the condition is true, the code block immediately following the if
statement is executed.
If the condition is false, the code block following the else keyword is
executed instead.
The if … else statement
An if statement with an else part allows for conditional execution of
code based on whether the condition specified in the if statement
evaluates to true or false.
If the condition is true, the code block immediately following the if
statement is executed.
If the condition is false, the code block following the else keyword is
executed instead.
The if else Statement
The if … else statement
Example-1 Example-2
<?php int number = 10;
if ($bank_balance < 100){ if (number > 5) {
$money = 1000; System.out.println("Number
$bank_balance += $money; is greater than 5");
} } else {
else{ System.out.println("Number
$savings += 50; is not greater than 5");
$bank_balance −= 50; }
}
?>
The if … else if statement
• The if-else if-else statement allows for branching behavior based on
multiple conditions.
• It's useful when you have several conditions to check, and you want to
execute different blocks of code depending on which condition(s)
evaluate to true.
if (condition1) {
// code block to execute if condition1 is true
} else if (condition2) {
// code block to execute if condition1 is false and
condition2 is true
} else {
// code block to execute if both condition1 and
condition2 are false
}
The if … else if statement
How it works?
• If condition1 is true, the code block within the first if statement is
executed, and the rest of the else if and else blocks are skipped.
• If condition1 is false and condition2 is true, the code block within the
else if statement is executed, and the else block is skipped.
• If both condition1 and condition2 are false, the code block within the
else statement is executed.
The if … else if statement
Example:
<?php
if ($bank_balance < 100){
$money = 1000;
$bank_balance += $money;
}
elseif ($bank_balance > 200){
$savings += 100;
$bank_balance −= 100;
}
else{
$savings += 50;
$bank_balance −= 50;
}
?>
The if … else if statement
Note:
• You can leave out a final else if it is not required, but you cannot have
one before an elseif; neither can you have an elseif before an if
statement.
• You may have as many elseif statements as you like.
• But as the number of elseif statements increases, you would probably be
better advised to consider a switch statement if it fits your needs
The switch statement
• The switch statement is a control flow statement in PHP that allows
you to execute different blocks of code based on the value of an
expression.
• It provides an alternative to using multiple if-else statements when you
have multiple conditions to check against the same variable.
The switch statement
• Syntax:
switch ($expression) {
case $value1:
// code block to execute if expression equals value1
break;
case $value2:
// code block to execute if expression equals value2
break;
// Additional cases...
default:
// code block to execute if expression doesn't match any case
The switch statement
• How it works:
• The switch statement evaluates the $expression and then compares its
value with the values specified in the case labels.
• If a match is found, the corresponding code block is executed.
Execution continues until a break statement is encountered or until the
end of the switch statement.
• If no match is found, the code block within the default label (if
provided) is executed.
• The break statement is used to exit the switch statement after a match
is found. If break is omitted, execution will "fall through" to the next
case statement, potentially leading to unexpected behavior.
The switch statement
• How it works:
• The switch statement evaluates the $expression and then compares its
value with the values specified in the case labels.
• If a match is found, the corresponding code block is executed.
Execution continues until a break statement is encountered or until the
end of the switch statement.
• If no match is found, the code block within the default label (if
provided) is executed.
• The break statement is used to exit the switch statement after a match
is found. If break is omitted, execution will "fall through" to the next
case statement, potentially leading to unexpected behavior.
The switch statement
<?php
if ($page == "Home") echo "You selected Home";
elseif ($page == "About") echo "You selected About";
elseif ($page == "News") echo "You selected News";
elseif ($page == "Login") echo "You selected Login";
elseif ($page == "Links") echo "You selected Links";
?>
This can be modified using a switch statement as →
The switch statement
<?php
switch ($page) case "Login":
{ echo "You selected Login";
case "Home": break;
echo "You selected Home"; case "Links":
break; echo "You selected Links";
case "About": break;
echo "You selected About"; }
break; ?>
case "News":
echo "You selected News";
break;
Alternative Syntax
<?php
switch ($page):
case "Home":
echo "You selected Home";
break;
// etc...

case "Links":
echo "You selected Links";
break;
endswitch;
?>
Loops
• One of the great things about computers is that they can repeat
calculating tasks quickly and tirelessly.
• Often you may want a program to repeat the same sequence of code
again and again until something happens, such as a user inputting a
value or reaching a natural end.
• PHP’s various loop structures provide the perfect way to do this.
While Loop
• The while loop in PHP is used to execute a block of code repeatedly as
long as a specified condition evaluates to true.
• Syntax:
while (condition) {
// Code to be executed while the condition is true
}
• condition: This is the condition that is evaluated before each iteration of
the loop. If the condition evaluates to true, the code block inside the
loop will be executed.
• If the condition evaluates to false, the loop will terminate, and the
program will continue executing the code after the loop.
• 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 {}.
While Loop
<?php
$counter = 1; // Initialize a counter variable

while ($counter <= 5) { // Loop as long as counter is less than or equal to 5


echo $counter. " "; // Output the current value of the variable counter
$counter++; // Increment the counter variable
}

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

Example for Indexed Array Example for Associative Array


Arrays
• To refer to a specific value in an array, start with the array variable
name, followed by the key within square brackets:
$band = $artists[0]; // The Mynabirds
echo $states['MD']; // Maryland
• Note that the array keys are used like other values in PHP: numbers
(e.g., 0) are never quoted, whereas strings (MD) must be.
• Because arrays use a different syntax than other variables, and can
contain multiple values, printing them can be trickier.
• This will not work
echo "My list of states: $states";
Arrays
• However, printing an individual element’s value is simple if it uses
indexed (numeric) keys:
echo "The first artist is $artists[0].";
• But if the array uses strings for the keys, the quotes used to surround
the key will confuse the syntax.
The following code will cause a parse error
echo "IL is $states['IL']."; // BAD!
To fix this, wrap the array name and key in curly braces when an array
uses strings fo its keys C:
echo "IL is {$states['IL']}.";
Superglobal Arrays
• PHP includes several predefined arrays called the superglobal variables.
They are: $_GET, $_POST, $_REQUEST, $_SERVER, $_ENV,
$_SESSION, and $_COOKIE.
• The $_GET variable is where PHP stores all of the values sent to a PHP
script via the GET method (possibly from an HTML form).
• $_POST stores all of the data sent to a PHP script from an HTML form that
uses the POST method.
• $_REQUEST is a superglobal array in PHP that contains the contents of
$_GET, $_POST, and $_COOKIE arrays.
• It is a convenient way to access data submitted via HTTP request, regardless
of whether it was sent through the URL query string (GET method),
through a form using the POST method, or via HTTP cookies.
Superglobal Arrays
• $_COOKIE: This is an associative array containing variables passed to the
current script via HTTP Cookies.
• Cookies are small pieces of data sent from a website and stored on the user's
computer by the user's web browser while the user is browsing.
• They are often used for tasks such as tracking user activity, maintaining user
preferences, and implementing features like shopping carts in e-commerce
websites.
• $_ENV: This is an array containing variables passed to the current script via
the environment method. These variables are typically set by the server
software or by the system itself.
• They can include information such as the path to certain system directories,
environmental settings, and more.
Superglobal Arrays
• $_SERVER: This is an array containing information such as headers, paths,
and script locations.
• It provides information about the server and environment under which the
current script is executing.
• Common elements include the script name, request method (GET, POST,
etc.), IP address of the client, and more.
• $_SESSION: This is an associative array containing session variables available
to the current script.
• It is used to store user-specific information across multiple pages or
requests. Sessions are typically used for tasks such as authentication,
tracking user preferences, and maintaining stateful information.
Use of Superglobal Variables
<?php
// Print the submitted information:
if ( !empty($_POST['name']) && !empty($_POST['comments']) &&
!empty($_POST['email']) )
{
echo "<p>Thank you, <b>{$_POST['name']}</b>, for the following
comments:<br />
<tt>{$_POST['comments']}</tt></p>
<p>We will reply to you at <i>{$_POST['email']}</i>.</p>\n";
else{
else {
echo '<p>Please go back and fill out the form again.</p>’; }
?>
Creating Arrays
• There are two primary ways to define your own array. First, you could add
an element at a time to build one:
$band[] = 'Jemaine';
$band[] = 'Bret';
$band[] = 'Murray';
• As arrays are indexed starting at 0, $band[0] has a value of Jemaine;
$band[1], Bret, and $band[2], Murray.
Creating Arrays
• you can specify the key when adding an element.
• But it’s important to understand that if you specify a key and a value already
exists indexed with that same key, the new value will overwrite the existing
one:
$band['fan'] = 'Mel';
$band['fan'] = 'Dave'; // New value
$fruit[2] = 'apple';
$fruit[2] = 'orange'; // New value
Creating Arrays
• Instead of adding one element at a time, you can use the array( ) function to
build an entire array in one step:
$states = array (
'IA' => 'Iowa',
'MD' => 'Maryland’
);
// Creating an indexed array
$fruits = array("Apple", "Banana", "Orange");
// Creating an indexed array
$fruits = array("Apple", "Banana", "Orange");
// Creating an associative array
$person = array("name" => "John", "age" => 30, "city" => "New
York");
Creating Arrays
• Instead of adding one element at a time, you can use the array( ) function to
build an entire array in one step:
$states = array (
'IA' => 'Iowa',
'MD' => 'Maryland’
);
// Creating an indexed array
$fruits = array("Apple", "Banana", "Orange");
// Creating an indexed array
$fruits = array("Apple", "Banana", "Orange");
// Creating an associative array
$person = array("name" => "John", "age" => 30, "city" => "New
York");
Creating Arrays
• If you set the first numeric key value, the added values will be keyed
incrementally thereafter:
$days = array (1 => 'Sun', 'Mon','Tue');
echo $days[3]; // Tue
• The array( ) function is also used to initialize an array, before referencing it:
$tv = array( );
$tv[ ] = 'Flight of the Conchords';
• Initializing an array (or any variable) in PHP isn’t required, but it makes for
clearer code and can help avoid errors.
• If you want to create an array of sequential numbers, you can use the
range( ) function:
$ten = range (1, 10);
Accessing Entire Array
• when you know exactly what the keys are or if you want to refer to only a
single element.
• To access every array element, use the foreach loop:
foreach ($array as $value) {
// Do something with $value.
}
• The foreach loop will iterate through every element in $array, assigning each
element’s value to the $value variable. To access both the keys and values, use
foreach ($person as $key => $value) {
echo $key . ": " . $value . ", ";
}
// Output: name: John, age: 30, city: New York,
Accessing Entire Array
• To determine the number of elements inan array, use count( ):
$num = count($array);
• The range( ) function can also create an array of sequential letters:
$alphabet = range ('a', 'z');
• An array’s key can be multiple-worded strings, such as first name or phone
number.
• The is_array( ) function confirms that a variable is of the array type.
• If you see an Invalid argument supplied for foreach( ) error message, that
means you are trying to use a foreach loop on a variable that is not an array
Example
Create the following interface using arrays
Accessing Entire Array
echo '<select name="month">';
foreach ($months as $key => $value) {
echo "<option value=\"$key\"> $value</option>\n";
}
echo '</select>’

echo '<select name="day">';


foreach ($days as $value) {
echo "<option value=\"$value\">$value</option>\n";
}
The Session Variables
• A session variable is a mechanism provided by web servers to store
information about a user across multiple pages or interactions with a
website.
• It allows data to be preserved and accessible throughout a user's browsing
session.
• Session variables provide a convenient and secure way to maintain state
information across multiple page requests during a user's visit to a website
• They are widely used in web development for tasks such as user
authentication, storing user preferences, managing shopping carts, and
more.
Session Vs Server Variables
• Purpose: Session variables are used to store data specific to a particular
user's session on a website. They maintain state across multiple page
requests during the same session.
• Storage: Session variables are stored on the server and are associated with
a unique session ID. The session ID is typically stored in a cookie on the
client side.
• Scope: Session variables are specific to each user's session. Changes made
to session variables by one user do not affect the session variables of other
users.
• Example Usage: Storing user authentication status, maintaining
shopping cart contents, remembering user preferences, etc.
Session Vs Server Variables
• Purpose: Server variables provide information about the server environment,
the client's request, and other HTTP headers. They are accessible from
anywhere in the PHP script.
• Storage: Server variables are predefined arrays provided by PHP, such as
$_SERVER, $_GET, $_POST, $_COOKIE, $_FILES, and $_REQUEST.
They contain information passed from the client's request, server
environment variables, cookies, form data, uploaded files, etc.
• Scope: Server variables are global and accessible from any part of the PHP
script.
• Example Usage: Retrieving form data submitted via HTTP POST
($_POST['fieldname']), accessing cookies sent by the client
($_COOKIE['cookiename']), etc.
Arrays Continued
• Indexed v/s Associative arrays,
• Multidimensional arrays,
• Creating Array,
• Accessing Array,
• Manipulating Arrays,
• Displaying array,
• Using Array Functions,
• Including and Requiring Files- use of Include() and Require()
• Implicit and Explicit Casting in PHP
Book 2 Chapter 6 Page No 131 to 144
Arrays
• Arrays are an example of what has made PHP so popular.
• Not only do they remove the dullness of writing code to deal with
complicated data structures, they also provide numerous ways to access data
while remaining amazingly fast.
• Some arrays are referenced by numeric indices; others allow alphanumeric
identifiers.
• Built-in functions let you sort them, add or remove sections, and walk
through them to handle each item through a special kind of loop.
• By placing one or more arrays inside another, you can create arrays of two,
three, or any number of dimensions.
Numerically Arrays
<?php
$paper[] = "Copier";
$paper[] = "Inkjet";
$paper[] = "Laser";
$paper[] = "Photo";
print_r($paper);
?>
• In this example, each time you assign a value to the array $paper, the first
empty location within that array is used to store the value, and a pointer
internal to PHP is incremented to point to the next free location, ready for
future insertions.
Numerically Indexed Arrays
<?php
$paper[] = "Copier";
$paper[] = "Inkjet";
$paper[] = "Laser";
$paper[] = "Photo";
print_r($paper);
?>
• In this example, each time you assign a value to the array $paper, the first
empty location within that array is used to store the value, and a pointer
internal to PHP is incremented to point to the next free location, ready for
future insertions.
• The print_r function (which prints out the contents of a variable, array, or
object)
Numerically Indexed Arrays
// Using array() function
$numbers1 = array(10, 20, 30, 40, 50);
// Using square brackets []
$numbers2 = [10, 20, 30, 40, 50];
• You can access elements of a numerically indexed array using square brackets
[] with the index of the element you want to access:
echo $numbers1[0]; // Output: 10
echo $numbers2[3]; // Output: 40
Numerically Indexed Arrays
• You can modify elements of a numerically indexed array by assigning a new
value to a specific index:
$numbers1[2] = 35;
echo $numbers1[2]; // Output: 35
• You can add elements to a numerically indexed array by specifying a new
index:
$numbers1[] = 60;
echo $numbers1[5]; // Output: 60
Associative Arrays
<?php
$paper['copier'] = "Copier & Multipurpose";
$paper['inkjet'] = "Inkjet Printer";
$paper['laser'] = "Laser Printer";
$paper['photo'] = "Photographic Paper";
echo $paper['laser'];
?>
• In place of a number (which doesn’t convey any useful information, aside
from the position of the item in the array), each item now has a unique name
that you can use to reference it elsewhere.
• The echo statement in the above example simply prints out Laser Printer.
• The names (copier, inkjet, etc.) are called indexes or keys and the items
• assigned to them (such as “Laser Printer”) are called values
Associative Arrays
• This very powerful feature of PHP is often used when you are extracting information
from XML and HTML.

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

Exploding a string delimited with *** into an array


<?php
$temp = explode('***', "A***sentence***with***asterisks");
print_r($temp);
?>
extract()
• Sometimes it can be convenient to turn the key/value pairs from an array
into PHP variables.
• One such time might be when you are processing the $_GET or $_POST
variables as sent to a PHP script by a form.
• When a form is submitted over the Web, the web server unpacks the
variables into a global array for the PHP script.
• If the variables were sent using the GET method, they will be placed in an
associative array called $_GET;
• If they were sent using POST, they will be placed in an associative array
called $_POST.
extract()
• Sometimes if you want to store the values sent into variables
for later use.
• In this case, you can have PHP do the job automatically for you:
extract($_GET);
• Be careful with this approach, though, because if any extracted variables
conflict with ones that you have already defined, your existing values will
be overwritten.
• To avoid this possibility, you can use one of the many additional parameters
available to this function, like this:
extract($_GET, EXTR_PREFIX_ALL, 'fromget');
compact()
There are also times when you want to use compact, the inverse of extract, to
create an array from variables and their values. Example 6-14 shows how you
might use this function.
Example 6-14. Using the compact function
<?php
$fname = "Doctor";
$sname = "Who";
$planet = "Gallifrey";
$system = "Gridlock";
$constellation = "Kasterborous";
$contact = compact('fname', 'sname', 'planet', 'system',
'constellation');
print_r($contact);
?>
reset()
• When the foreach ... as construct or the each function walks through an array,
it keeps an internal PHP pointer that makes a note of which element of the
array it should return next.
• If your code ever needs to return to the start of an array, you can issue
• reset, which also returns the value of that element.

Examples of how to use this function are:


reset($fred); // Throw away return value
$item = reset($fred);
// Keep first element of the array in $item
end()
• Using the end() function you can move PHP’s internal array pointer to
the final element in an array using the end function, which also returns
the value of the element, and can be used as in these examples:
end($fred);
$item = end($fred);

Array_Eg
Dummy_proj

You might also like