Professional Documents
Culture Documents
Chapter 5
PHP 7 Functions & Arrays
What is output of the following
<?php
$a=1; $b=2;$c=3; $d=1;
for ($i=1 ; $i<=8;$i+=3)
{
$a += $b * $i;
$b = $a *2;
$c +=$a - $b;
echo "A=".$a." B= ".$b." C=".$c."<br>";
}
$d = $d++ + ++$d;
echo $d;
?>
PHP 7 Functions
• The real power of PHP comes from its functions; it has
more than 1000 built-in functions.
• PHP User Defined Functions
• Besides the built-in PHP functions, we can create our
own functions.
• A function is a block of statements that can be used
repeatedly in a program.
• A function will not execute immediately when a page
loads.
• A function will be executed by a call to the function.
Create a User Defined Function in PHP
• <?php
function writeMsg() {
echo "Hello world!";
}
• <?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
• The following example has a function with two arguments
($fname and $year):
• Example
• <?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
PHP is a Loosely Typed Language
• In the example above, notice that we did not have to tell PHP
which data type the variable is.
• PHP automatically associates a data type to the variable,
depending on its value. Since the data types are not set in a strict
sense, you can do things like adding a string to an integer without
causing and error.
• In PHP 7, type declarations were added. This gives us an option to
specify the data type expected when declaring a function, and by
enabling the strict requirement, it will throw a "Fatal Error" on a
type mismatch.
• In the following example we try to add a number and a string
with without the strict requirement:
Example
• <?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is
changed to int(5), and it will return 10
?>
Example
• In the following example we try to add a number and a string
with the strict requirement:
• Example
• <?php declare(strict_types=1); // strict requirement
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions - Returning values
• <?php declare(strict_types=1); // strict
requirement
function addNumbers(float $a, float $b) : float
{
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
• You can specify a different return type, than the argument
types, but make sure the return is the correct type:
• Example:
• <?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int
{
return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>
PHP 7 Arrays
• <?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " .
$cars[2] . ".";
?>
Get The Length of an Array
• The count() Function
• The count() function is used to return the
length (the number of elements) of an array:
• 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);
• <?php
• /* First method to create an associate array. */
• $student_one = array("Maths"=>95, "Physics"=>90,
• "Chemistry"=>96, "English"=>93,
• "Computer"=>98);
• /* Second method to create an associate array. */
• $student_two["Maths"] = 95; $student_two["Physics"] = 90;
$student_two["Chemistry"] = 96;
• $student_two["English"] = 93; $student_two["Computer"] =
98;
•
• /* Accessing the elements directly */
• echo "Marks for student one is:\n";
• echo "Maths:" . $student_two["Maths"], "\n";
• echo "Physics:" . $student_two["Physics"], "\n";
• echo "Chemistry:" . $student_two["Chemistry"], "\n";
• echo "English:" . $student_one["English"], "\n";
• echo "Computer:" . $student_one["Computer"], "\n";
• ?>
Traversing the Associative Array:
• We can traverse associative arrays using loops.
We can loop through the associative array in
two ways. First by using for loop and secondly
by using foreach.
• Example:
Here array_keys() function is used to find
indices names given to them
and count() function is used to count number
of indices in associative arrays.
• <?php
• /* Creating an associative array */
• $student_one = array("Maths"=>95, "Physics"=>90,
• "Chemistry"=>96, "English"=>93,
• "Computer"=>98);
• /* Looping through an array using foreach */
• echo "Looping using foreach: \n";
• foreach ($student_one as $subject => $marks){
• echo "Student one got ".$marks." in ".$subject."\n";
• }
• /* Looping through an array using for */
• echo "\nLooping using for: \n";
• $subject = array_keys($student_one);
• $marks = count($student_one);
• for($i=0; $i < $marks; ++$i) {
• echo $subject[$i] . ' ' . $student_one[$subject[$i]] . "\n";
• }
• ?>
Creating an associative array of mixed types
• <?php
• /* Creating an associative array of mixed types */
• $arr["xyz"] = 95;
• $arr[100] = "abc";
• $arr[11.25] = 100;
• $arr["abc"] = "pqr";
•
• /* Looping through an array using foreach */
• foreach ($arr as $key => $val){
• echo $key."==>".$val."\n";
• }
• ?>
• Output:
• xyz==>95 100==>abc 11==>100 abc==>pqr
Multidimensional arrays in PHP
• Multi-dimensional arrays are such type of arrays
which stores an another array at each index
instead of single element. In other words, define
multi-dimensional arrays as array of arrays.
• As the name suggests, every element in this
array can be an array and they can also hold
other sub-arrays within.
• Arrays or sub-arrays in multidimensional arrays
can be accessed using multiple dimensions.
• Dimensions: Dimensions of multidimensional
array indicates the number of indices needed
• to select an element.
• For a two dimensional array two indices to
select an element.
• Two dimensional array: It is the simplest form
of a multidimensional array. It can be
EXAMPLE
• <?php
• $cars = array ( array("Volvo",22,18), array("BMW",15,13),
array("Saab",5,2), array("Land Rover",17,15));
• for ($row = 0; $row < 4; $row++) {
• echo "<p><b>Row number $row</b></p>";
• echo "<ul>";
• for ($col = 0; $col < 3; $col++) {
• echo "<li>".$cars[$row][$col]."</li>";
• }
• echo "</ul>";
• }
• ?>
• created using nested array. These type of arrays can be used to store any type
of
• elements, but the index is always a number. By default, the index starts with
zero.
• </p>
• Syntax:
• array (
• array (elements...),
• array (elements...),
• ...
• )
PHP 7 Sorting Arrays
• The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending.
• PHP - Sort Functions For Arrays
• In this chapter, we will go through the following PHP array sort functions:
1- sort() - sort arrays in ascending order
2- rsort() - sort arrays in descending order
3- asort() - sort associative arrays in ascending order, according to the value
ترتيب تصاعدي حسب القيم
4- ksort() - sort associative arrays in ascending order, according to the key
ترتيب تصاعدي حسب الفهرس
5- arsort() - sort associative arrays in descending order, according to the value
6- krsort() - sort associative arrays in descending order, according to the key
Sort Array in Ascending Order - sort()
• array_unshift($arr,100,200);
• print_r($arr);
• array_pop($arr);
• array_pop($arr);
• print_r($arr);
• array_shift($arr);
• array_shift($arr);
• array_shift($arr);
• for($i=0;$i<count($arr); $i++)
• echo $arr[$i]." ";echo "<br>";
• echo "<br>";echo "<br>";
• $fruits=array("ban"=>"banana",
"feg"=>"feg","tut"=>"strawbery", "kk"=>"koko",
11=>"wheat");
• foreach ($fruits as$value) echo $value." ";
• sort($arr);
• echo "<br> AFTER SORTING THE ARRAY IN ASCENDING ORDER";echo
"<br>";
• for($i=0;$i<count($arr); $i++)
• echo $arr[$i]." ";echo "<br>";
• rsort($arr);
• echo "<br> AFTER SORTING THE ARRAY IN DESCENDING ORDER";echo
"<br>";
• for($i=0;$i<count($arr); $i++)
• echo $arr[$i]." ";echo "<br>";
• ?>
Passing array to a function by reference
• To pass array by reference, only precede the
• array name in function head by & like this:
• function processArray(&$a)
• {
• array_push($a,"jamheeeeer");
• }
• $stack = array("orange", "banana");
• array_push($stack, "apple", "raspberry");
• array_push($stack, "melon", "analop", "patato");
• processArray($stack); // the function call statement
Passing array to a function by
value
• Arrays are passed by value by default. Just the array name
is specified without & as follows:
• function processArray($a)
• {
• array_push($a,"jamheeeeer");
• }
• $stack = array("orange", "banana");
• array_push($stack, "apple", "raspberry");
• array_push($stack, "melon", "analop", "patato");
• processArray($stack); // the function call statement
PHP Global Variables – Super globals
• Several predefined variables in PHP are "super globals", which means that
they are always accessible, regardless of scope - and you can access them
from any function, class or file without having to do anything special.
• The PHP super global variables are:
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION
PHP $GLOBALS
• $GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP
script (also from within functions or methods).
• PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
• The example below shows how to use the super global variable $GLOBALS:
• Example
• <?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
• In the example above, since z is a variable present within the $GLOBALS array, it is also accessible from
outside the function!
PHP $_SERVER
• $_SERVER is a PHP super global variable which holds information about headers,
paths, and script locations.
• The example below shows how to use some of the elements in $_SERVER:
• Example
• <?php
echo $_SERVER['PHP_SELF']; //Returns the filename of the currently executing script
echo "<br>";
echo $_SERVER['SERVER_NAME']; //Returns the name of the host server (such as
www.w3schools.com)
echo "<br>";
echo $_SERVER['HTTP_HOST']; //Returns the Host header from the current request
echo "<br>";
echo $_SERVER['SCRIPT_NAME']; //Returns the path of the current script
?>
• echo $_SERVER['REMOTE_ADDR']
//Returns the IP address from where the user is
viewing the current page.
echo $_SERVER[‘SCRIPT_URL’]; //Returns the
URI of the current page
The correct format
• define('ENVIRONMENT', 'developent');
• echo $_SERVER['PHP_SELF']."<BR>";
• echo $_SERVER['SERVER_NAME']."<BR>";
• echo $_SERVER['HTTP_HOST']."<BR>";
• echo $_SERVER['SCRIPT_NAME']."<BR>";
• echo $_SERVER['REMOTE_ADDR']."<BR>";
• echo $ip_address = $_SERVER['REMOTE_ADDR']."<BR>";
• $url = $_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME'];
• echo $url."<BR>";
• ?>
PHP $_REQUEST
• <html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
PHP $_POST
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
PHP $_GET
• PHP $_GET can also be used to collect form data after submitting an HTML form
with method="get".
• $_GET can also collect data sent in the URL.
• Assume we have an HTML page that contains a hyperlink with parameters:
• <html>
<body>
</body>
</html>
• When a user clicks on the link "Test $GET", the parameters "subject" and "web" are
sent to "test_get.php", and you can then access their values in "test_get.php" with
$_GET.
• The example below shows the code in "test_get.php":
Example
• <html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at
" . $_GET['web'];
?>
</body>
</html>
implode() function
• The implode() function returns a string from the
elements of an array.
• Note: The implode() function accept its
parameters in either order. However, for
consistency with explode()
• <?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
explode() function
• The explode() function breaks a string into an
array. Note: The "separator" parameter
cannot be an empty string.
• <?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
shuffle() Function
• The shuffle() Function is a builtin function in PHP and is used
to shuffle or randomize the order of the elements in an array.
This function assigns new keys for the elements in the array. It
will also remove any existing keys, rather than just reordering
the keys and assigns numeric keys starting from zero.
• Randomize the order of the elements in the array:
• <?php
$my_array = array("red","green","blue","yellow","purple");
shuffle($my_array);
print_r($my_array);
?>
• <?php
• // input array contain some elements which // need to be shuffled.
• $a = array
• (
• "a"=>"Ram", "b"=>"Shita", "c"=>"Geeta", "d"=>"geeksforgeeks;
• shuffle($a);
• print_r($a);
• ?>