0% found this document useful (0 votes)
67 views13 pages

PHP Arrays and Include/Require Guide

The document discusses PHP arrays, include/require statements, and functions. It provides examples of: - Creating indexed, associative, and multidimensional arrays and looping through them - Using include and require to insert one PHP file into another for code reuse - Defining functions to organize reusable blocks of code that can accept parameters and return values

Uploaded by

hassan IQ
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)
67 views13 pages

PHP Arrays and Include/Require Guide

The document discusses PHP arrays, include/require statements, and functions. It provides examples of: - Creating indexed, associative, and multidimensional arrays and looping through them - Using include and require to insert one PHP file into another for code reuse - Defining functions to organize reusable blocks of code that can accept parameters and return values

Uploaded by

hassan IQ
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/ 13

Experiment No (7)

PHP part-2
objective;

in this experiment we will learn how to use :

 array in different type.


 include and require statements.
 function structure.

1- array
An array is a data structure that stores one or more values in a single value. For experienced programmers it
is important to note that PHP's arrays are actually maps (each key is mapped to a value).

 In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

1- PHP Indexed Arrays

There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0):

$cars=array("Volvo","BMW","Toyota");

or the index can be assigned manually:

$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";

 The count() function is used to return the length (the number of elements) of an array:

1|Page
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Loop Through an Indexed Array

To loop through and print all the values of an indexed array, you could use a for loop, like this:

Example
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
2- PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.

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
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop, like this:

2|Page
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

3- Multidimensional Arrays

A multidimensional array is an array containing one or more arrays.

In a multidimensional 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.

EX:
$row_0 = array(1, 2, 3);
$row_1 = array(4, 5, 6);
$row_2 = array(7, 8, 9);
$multi = array($row_0, $row_1, $row_2);
You can refer to elements of multidimensional arrays by appending more []s:
$value = $multi[2][0];

Example
<?php
$shop = array( array("rose", 1.25 , 15),
array("daisy", 0.75 , 25),
array("orchid", 1.15 , 7)
);
?>

To display elements of this array we could have organize manual access to each element or make it by putting
For loop inside another For loop:

<?php
echo "<h1>Manual access to each element</h1>";
echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2]."<br />";
echo $shop[1][0]." costs ".$shop[1][1]." and you get ".$shop[1][2]."<br />";
echo $shop[2][0]." costs ".$shop[2][1]." and you get ".$shop[2][2]."<br />";
echo "<h1>Using loops to display array elements</h1>";
echo "<ol>";

3|Page
for ($row = 0; $row < 3; $row++)
{
echo "<li><b>The row number $row</b>";
echo "<ul>";

for ($col = 0; $col < 3; $col++)


{
echo "<li>".$shop[$row][$col]."</li>";
}

echo "</ul>";
echo "</li>";
}
echo "</ol>";
?>

Perhaps, instead of the column numbers you prefer to create their names. For this purpose, you can use
associative arrays. The following code will store the same set of flowers using column names:

<?php
$shop = array( array( Title => "rose",
Price => 1.25,
Number => 15
),
array( Title => "daisy",
Price => 0.75,
Number => 25,
),
array( Title => "orchid",
Price => 1.15,
Number => 7
)
);
?>

It is easier to work with this array, in case you need to get a single value out of it. Necessary data can be easily
found, if you turn to a proper cell using meaningful row and column names that bear logical content.
However, we are losing the possibility to use simple for loop to view all columns consecutively.

<?php
echo "<h1>Manual access to each element from associative array</h1>";

4|Page
for ($row = 0; $row < 3; $row++)
{
echo $shop[$row]["Title"]." costs ".$shop[$row]["Price"]." and you get ".$shop[$row]["Number"];
echo "<br />";
}
echo "<h1>Using foreach loop to display elements</h1>";
echo "<ol>";
for ($row = 0; $row < 3; $row++)
{
echo "<li><b>The row number $row</b>";
echo "<ul>";
foreach($shop[$row] as $key => $value)
{
echo "<li>".$value."</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ol>";
?>

Three-dimensional Arrays
You don’t have to be limited by two dimensions: the same way as array elements can contain other arrays,
these arrays, in their turn, can contain new arrays.
Three-dimensional array is characterized by height, width, and depth. If you feel comfortable to imagine two-
dimensional array as a table, then imagine a pile of such tables. Each element can be referenced by its layer,
row, and column.
If we classify flowers in our shop into categories, then we can keep data on them using three-dimensional
array. We can see from the code below, that three-dimensional array is an array containing array of arrays:

<?php
$shop = array(array(array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 1.15, 7)
),
array(array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 1.15, 7)
),
array(array("rose", 1.25, 15),

5|Page
array("daisy", 0.75, 25),
array("orchid", 1.15, 7)
)
);
?>

As this array has only numeric indexes, we can use nested for loops to display it:

<?php
echo "<ul>";
for ( $layer = 0; $layer < 3; $layer++ )
{
echo "<li>The layer number $layer";
echo "<ul>";
for ( $row = 0; $row < 3; $row++ )
{
echo "<li>The row number $row";
echo "<ul>";
for ( $col = 0; $col < 3; $col++ )
{
echo "<li>".$shop[$layer][$row][$col]."</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ul>";
?>

PHP Sorting Arrays


PHP - Sort Functions For Arrays

In this chapter, we will go through the following PHP array sort functions:

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

6|Page
Sort Array in Ascending Order - sort()

The following example sorts the elements of the $cars array in ascending alphabetical order:

Example
<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
?>

Sort Array in Descending Order - rsort()

The following example sorts the elements of the $cars array in descending alphabetical order:

Example
<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>

The following example sorts an associative array in ascending order, according to the key:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>

2- PHP include and require Statements

In PHP, you can insert the content of one PHP file into another PHP file before the server executes it. The
include and require statements are used to insert useful codes written in other files, in the flow of execution.

Include and require are identical, except upon failure:

 require will produce a fatal error (E_COMPILE_ERROR) and stop the script
 include will only produce a warning (E_WARNING) and the script will continue

So, if you want the execution to go on and show users the output, even if the include file is missing, use
include. Otherwise, a complex PHP application coding, always use require to include a key file to the flow of
execution. This will help avoid compromising your application's security and integrity, just in-case one key
file is accidentally missing.

7|Page
Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for
all your web pages. Then, when the header needs to be updated, you can only update the header include file.

Syntax
include 'filename';
or
require 'filename';

Example 1:

Assume we have a standard menu file that should be used on all pages.

"menu.php":

echo '<a href="/default.php">Home</a>


<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>';

All pages in the Web site should include this menu file. Here is how it can be done:

<html>
<body>

<div class="leftmenu">
<?php include 'menu.php'; ?>
</div>

<h1>Welcome to my home page.</h1>


<p>Some text.</p>

</body>
</html>

Example 2

Assume we have an include file with some variables defined ("vars.php"):

<?php
$color='red';

8|Page
$car='BMW';
?>

Then the variables can be used in the calling file:

<html>
<body>

<h1>Welcome to my home page.</h1>


<?php include 'vars.php';
echo "I have a $color $car"; // I have a red BMW
?>
</body>
</html>

3- PHP Functions
A function is a self-contained block of code that can be called by your scripts. When called, the function's
code is executed. You can pass values to functions, which they then work with. When finished, a function can
pass a value back to the calling code.

PHP comes with hundreds of ready-made, built-in functions, making it a very rich language. To use a
function, call it by name. Some of the built-in functions that use one or more arguments appear in Example
below.
Example. Three string functions
<?php
echo strrev(" .dlrow olleH"); // Reverse string
echo str_repeat("Hip ", 2); // Repeat string
echo strtoupper("hooray!"); // String to uppercase
?>
This example uses three string functions to output the following text:
Hello world. Hip Hip HOORAY!

Defining a Function
The general syntax for a function is:
function function_name([parameter [, ...]])
{
// Statements
}
 The first line of the syntax indicates that:
• A definition starts with the word function.
• Following that is a name, which must start with a letter or underscore, followed by any number of letters,
numbers, or underscores.
• The parentheses are required.

9|Page
• One or more parameters, separated by commas, are optional (indicated by the square brackets, which are not
part of the function syntax).

Example:

<?php
function printBR( $txt ) {
print ( "$txt<br />\n" );
}
printBR("This is a line");
printBR("This is a new line");
printBR("This is yet another line");
?>

When you're creating your own functions, you may notice that they can be broken down in to two categories:
functions that you can leave, and just let them do their jobs; and functions where you need to get an answer
back. As an example, here's the two different categories in action:

print ("Get on with it!");


$string_length = strlen($string_length);

The print function is an example of a function that you can leave, and just let it do its job. You just tell it what
to print and it gets on with it for you. But a function like strlen( ) is not. You need something back from it –
the length of the string.

Suppose you had a function that worked out a 10 percent discount. But you only want to apply the discount if
the customer spent over 100 pounds. You could create a function that is handed the amount spent. Then check
to see if it's over a 100 pounds. If it is, the function calculates the discount; if not, don't apply the discount.
But in both cases, you want the function to return the answer to your question – What do I charge this
customer? Here's the script:

<?PHP
$total_spent = 120;
$order_total = calculate_total($total_spent);
print $order_total;
function calculate_total($total_spent) {
$discount = 0.1;
if ($total_spent > 100) {
$discount_total = $total_spent - ($total_spent * $discount);
$total_charged = $discount_total;
}
else {
$total_charged = $total_spent;
}
return $total_charged;
}
?>

10 | P a g e
Example

<?php
function addNums( $firstnum, $secondnum ) {
$result = $firstnum + $secondnum;
return $result;
}
print addNums(3,5);
// will print "8"
?>

Dynamic Function Calls

You can assign function names as strings to variables and then treat these variables exactly as you would the
function name itself.

<html>
<head>
<title> Calling a Function Dynamically</title>
</head>
<body>
<div>
<?php
function sayHello() {
print "hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</div>
</body>
</html>
Accessing Variables with the global Statement

From within a function, by default you can't access a variable that has been defined elsewhere. If you attempt
to use a variable of the same name, you will set or access a local variable only.

<?php
$life = 42;
function meaningOfLife() {
print "The meaning of life is $life<br />";
}
meaningOfLife();
?>

11 | P a g e
the output of the example is:
the meaning of life is
however, if we want to access an important global variable from within a function without passing it in as an
argument. This is where the global statement comes into its own.

A Function with an Optional Argument

<?php
function headingWrap( $txt, $size=3 ) {
print "<h$size>$txt</h$size>";
}
headingWrap("Book title", 1);
headingWrap("Chapter title",2);
headingWrap("Section heading");
headingWrap("Another Section heading");
?>

Passing References to Variables to Functions

When you pass arguments to functions, they are stored as copies in parameter variables. Any changes made to
these variables in the body of the function are local to that function and are not reflected beyond it.

<?php
function addFive( $num ) { ----------------------------------------------------> function addFive( &$num )
$num += 5;
}
$orignum = 10;
addFive( $orignum );
print( $orignum );
?>
Returning References from Functions
Functions return by value. So, if you pass a variable to a function by reference and then return that variable to
the calling code, you return a copy of the variable's value. You do not, by default, return a variable reference.
You can change this behavior by prepending an ampersand to the name of your function, like so:

function &addFive( &$num ) {


$num+=5;
return $num;
}
$num is now both passed to addFive() and returned from it by reference. We can illustrate this by calling
addFive():

$orignum = 10;
$retnum = & addFive( $orignum );
$orignum += 10;
print( $retnum ); // prints 25

12 | P a g e
Creating Anonymous Functions

You can create functions on-the-fly during script execution. Because such functions are not themselves given
a name but are stored in variables or passed to other functions, they are known as anonymous functions. PHP
provides the create_function() function for creating anonymous functions; it requires two string arguments.
The first argument should contain a comma-delimited list of argument variables, exactly the same as the
argument variables you would include in a standard function declaration. The second argument should contain
our function body.

<?php
$my_anon = create_function( '$a, $b', 'return $a+$b;' );
print $my_anon( 3, 9 );
?>

assignment:

1- Create a function that accepts four string variables and returns a string that contains an HTML table
element, enclosing each of the variables in its own cell.
2- write a PHP program to determine the following array by using function structural
2 4 6 8 10
2 6 24 120 720
1 3 5 7 9

3- write PHP program to read 10 numbers by using form then displayed them in ascending order, by using
function structural.

13 | P a g e

You might also like