module 3
module 3
Emerging Technologies
MODULE 3
PHP Arrays and User Defined
Functions
PHP Arrays and User Defined Functions
Objectives
• To know the different approach of using arrays in PHP.
• To be familiar with using print_r function and var_dump
function for array inspection.
• To use PHP lazy function foreach to iterate through array
elements.
• To implement one dimensional and multi-dimensional in the
program.
• To know what is associative array in PHP.
• To use different predefined functions in manipulating array
elements.
• To defined what is function and to use function keyword in
declaring function in PHP.
• To create a user defined function using different approach.
PHP Arrays and User Defined Functions
Objectives (continue)
• To know use variables that is globally declared and locally
declared.
• To create static variables that can be used in accumulating
data every time the function calls.
PHP Arrays
PHP Arrays and User Defined Functions
Array
is used to aggregate a series of similar items together, arranging and
dereferencing them in some specific way.
print_r() function
short for print recursive. This takes an argument of any type
and prints it out, which includes printing all its parts
recursively.
var_dump() function
is same as the print_r function except that it prints additional
information about the size and type of the values it discovers
foreach() function
is a statement used to iterate or loop through the element in an
array. With each loop, a foreach statement moves to the next
element in an array.
foreach statement
specify an array expression within a set of parenthesis
following the foreach keyword.
Syntax
PHP Arrays and User Defined Functions
Example: Output:
PHP Arrays and User Defined Functions
Example:
Output:
PHP Arrays and User Defined Functions
Example:
PHP Arrays and User Defined Functions
Arrays: Sorting
Function Description
sort($array) Sorts by value; assign new numbers as the keys
rsort($array) Sorts by value in reverse order; assign new number
as the keys
asort($array) Sorts by value; keeps the same key
arsort($array) Sorts by value in reverse order; keeps the same key
ksort($array) Sorts by key
krsort($array) Sorts by key in reverse order
usort($array, Sorts by a function
functionname)
PHP Arrays and User Defined Functions
Arrays: Sorting
Example: Output:
PHP Arrays and User Defined Functions
Arrays: Sorting
Example: Output:
PHP Arrays and User Defined Functions
Arrays: Sorting
Example: Output:
PHP User Defined Functions
PHP Arrays and User Defined Functions
Functions
is a group of PHP statements that performs a specific task. Functions are
designed to allow you to reuse the same code in different locations.
Predefined functions
functions that are built-in into PHP to perform some standard operations
PHP Arrays and User Defined Functions
Syntax
function name(param){
//code to be executed by the function
}
Where
function – is the keyword used to declare a function
name – is the name of the function or function
identifier
param – is the formal parameters of the function.
Parameter must follow the rule of naming
dentifier.
PHP Arrays and User Defined Functions
Example: Output:
Slide 22
PHP Arrays and User Defined Functions
Example: Output:
PHP Arrays and User Defined Functions
Example: Output:
PHP Arrays and User Defined Functions
Example:
Output:
Example: Output:
PHP Arrays and User Defined Functions
Global Variables
is one that declared outside a function and is available to all
parts of the program.
Local Variables
is declared inside a function and is only available within the
function in which it is declared.
Static Variables
is used to retain the values calls to the same function.
PHP Arrays and User Defined Functions
Example: Output:
Example: Output:
PHP Arrays and User Defined Functions
Example: Output:
Example: Output:
PHP Arrays and User Defined Functions
Example:
Output:
An introduction to PHP web programming
Summary
• Array is used to aggregate a series of similar items together.
• Array index references a corresponding value.
• Array index can be simple numerical or have some direct
correlation to the value.
• Array index is also known as Array Keys.
• print_r function is used to print the array structure.
• var_dump function is same as print_r function except it adds
additional information about the data of each element.
• The foreach statement is use to iterate through the element in an
array.
• Using foreach statement you can display both the keys and value
of each element in the array.
• PHP provides functions for array manipulation such as sort(),
rsort(), asort(), arsort(), ksort(), krsort(), and usort() functions.
An introduction to PHP web programming
Summary (continue)
• sort(), asort(), and ksort() functions are used to sort elements in the
array in ascending order.
• rsort(), arsort(), and krsort() functions are used to sort elements in
the array in descending order.
• sort() and rsort() does not maintain its index reference for each
values.
• asort(), ksort(), arsort(), and krsort() maintains its reference for each
values.
• asort() and arsort() used to sort elements by values.
• ksort() and krsort() used to sort elements by keys.
• Functions is a group of PHP statements that performs a specific
task.
• Functions can be user defined generally defined by the user of the
program and predefined that are build in using libraries.
An introduction to PHP web programming
Summary (continue)
• You use functions in different ways. Function can only do
something without passing values. You can pass values to a
function and you can ask functions to return a value.
• function keyword is used in PHP to declare a function.
• A function that is declared inside a function is said to be hidden.
• To gain access to a variable that is outside from the function we
use the global keyword.
• We use static keyword to declare a variable inside a function that
will act as accumulator variable this will let the program remember
the last value of the variable that was used.
What is Array?
An array is a data structure that stores one or more similar type of values in a single
value. For example if you want to store 100 numbers then instead of defining 100
variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c
which is called array index.
• Numeric array − An array with a numeric index. Values are stored and
accessed in linear fashion.
• Associative array − An array with strings as index. This store element values in
association with key values rather than in a strict linear index order.
• Multidimensional array − An array containing one or more arrays and values
are accessed using multiple indices
NOTE − Built-in array functions is given in function reference PHP Array Functions
Numeric Array
These arrays can store numbers, strings and any object but their index will be
represented by numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in
function reference.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
</body>
</html>
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000,
"zara" => 500);
</body>
</html>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
</body>
</html>
What is an Array?
• An array is an ordered collection of elements. Each element has a value, and is
identified by a key. Each array has its own unique keys.
• The keys can be either integer numbers or strings.
Examples:
<?php
$vec_1 = array(2,4,5);
echo "<BR><BR>"."simple array of numbers";
for($i=0; $i<3; $i++)
{
echo "<BR>".$vec_1[$i];
}
?>
<?php
$vec_1 = array("moshe","david","john");
echo "simple array of strings";
for($i=0; $i<3; $i++)
{
echo "<BR>".$vec_1[$i];
}
?>
<?php
$vec_1 = array(100=>"moshe",101=>"david",102=>"john");
echo "simple array of strings and their keys";
echo "<BR>".$vec_1[100];
echo "<BR>".$vec_1[101];
echo "<BR>".$vec_1[102];
?>
<?php
$vec_1 = array("m"=>"moshe","d"=>"david","j"=>"john");
echo "simple array of strings and their keys";
echo "<BR>".$vec_1["m"];
echo "<BR>".$vec_1["d"];
echo "<BR>".$vec_1["j"];
?>
<?php
$vec = array(2,4,5,123,2221,”sda”);
var_dump($vec);
?>
• Using var_dump() function we can print out more than one array.
<?php
$vec_1 = array(2,4,5,123,2221);
$vec_2 = array(24,442,32,84,110);
$vec_3 = array(10,20,30,40,50);
var_dump($vec_1,$vec_2,$vec_3);
?>
<?php
class Rectangle {}
$vec_1 = array(2,4,5,123,”fofo”,new Rectangle());
print_r($vec_1);
?>
Array Inner Structure
• PHP arrays behave like ordered map. As such, they allow various possibilities:
PHP arrays can be used to simulate different types of structures (e.g. map, queue, stack etc...).
PHP arrays can have unique keys, both numeric and textual. When using numeric ones, they
don't need to be sequential.
<?php
$matrix = array();
$matrix[0] = array("a","b");
$matrix[1] = array("c","d");
echo $matrix[0][0];
echo $matrix[0][1];
echo $matrix[1][0];
echo $matrix[1][1];
?>
<?php
$info = array('moshe', 'david', 'michael','john');
list($operation_manager, $marketing_manager, ,$finance_manager) = $info;
echo "<BR>operation department manager is $operation_manager";
echo "<BR>finance department manager is $finance_manager";
echo "<BR>marketing department manager is $marketing_manager";
?>
<?php
$vec = [2=>"dave",1=>"ron",0=>"chen",3=>"ran"];
list($a,$b,$c) = $vec;
echo "<br>a=$a";
echo "<br>b=$b";
echo "<br>c=$c";
?>
• As of PHP 5.5 we can use the list construct together with the foreach loop.
<?php
$matrix = [
["haim", "michael", 344537565],
["mosh", "solomon", 452234343],
["ron","kalmon",453234234]
];
foreach ($matrix as list($fname, $lname,$id))
{
echo "fname:$fname lname:$lname id:$id ";
}
?>
<?php
$vec_1 = array(1,2,3);
$vec_2 = array(3,4,5,6);
$vec_3 = $vec_1 + $vec_2;
var_dump($vec_3);
?>
The '===' operator (non identity) returns true if each one of the following two conditions fulfills:
1. The two arrays contain the same elements.
2. The two arrays have their identical elements in the same position.
<?php
//$a = ['a'=>'avodado','b'=>'bamba','c'=>'calco'];
//$b = ['b'=>'bamba','a'=>'avodado','c'=>'calco'];
$a = [123,455,323];
$b = [323,123,455];
if($a==$b)
{
echo "a and b equal";
}
else
{
echo "a and b not equal";
}
?>
Result: a and b not equal
The '!==' operator (non identity) returns true if at least one of the following two conditions doesn't
fulfill:
2. The two arrays have their identical elements in the same position.
Example
<?php
$vec_1 = array(1,2,3);
$vec_2 = array(1,2,3);
$vec_3 = array(0=>1, 1=>2, 2=>3);
$vec_4 = array(12=>1, 3=>2, 4=>3);
$vec_5 = array(1=>2, 0=>1, 2=>3);
var_dump($vec_1==$vec_2); //true
var_dump($vec_1===$vec_2); //true
var_dump($vec_1!=$vec_2); //false
var_dump($vec_1!==$vec_2); //false
echo "<BR>";
var_dump($vec_2==$vec_3); //true
var_dump($vec_2===$vec_3); //true
var_dump($vec_2!=$vec_3); //false
var_dump($vec_2!==$vec_3); //false
?>
Example
<?php
echo "<BR>";
var_dump($vec_2==$vec_4); //false
var_dump($vec_2===$vec_4); //false
var_dump($vec_2!=$vec_4); //true
var_dump($vec_2!==$vec_4); //true
echo "<BR>";
var_dump($vec_2==$vec_5); //true
var_dump($vec_2===$vec_5); //false
var_dump($vec_2!=$vec_5); //false
var_dump($vec_2!==$vec_5); //true
?>
<?php
$vec = array(1,2,3,4,5,6,7,8);
echo count($vec);
?>
<?php
$vec_1 = array(1,2,3,4,5,6,7,8);
$vec_2 = 123;
if(is_array($vec_1))
echo "<BR>vec_1 is an array";
else
echo "<BR>vec_1 is not an array";
if(is_array($vec_2))
echo "<BR>vec_2 is an array";
else
echo "<BR>vec_2 is not an array";
?>
The isset() Function
Calling the isset() function can tell us if a specific key already exists in our array... or not.
<?php
$vec = array('a'=>1,'b'=>2,'c'=>3);
if(isset($vec['a'])) echo "<BR>'a' key exists";
if(isset($vec['b'])) echo "<BR>'b' key exists";
if(isset($vec['c'])) echo "<BR>'c' key exists";
if(isset($vec['d'])) echo "<BR>'d' key exists";
if(isset($vec['e'])) echo "<BR>'e' key exists";
?>
<?php
$vec = array('a'=>1,'b'=>2,'c'=>3);
if(array_key_exists('a',$vec)) echo "<BR>'a' key exists";
if(array_key_exists('b',$vec)) echo "<BR>'b' key exists";
if(array_key_exists('c',$vec)) echo "<BR>'c' key exists";
if(array_key_exists('d',$vec)) echo "<BR>'d' key exists";
if(array_key_exists('e',$vec)) echo "<BR>'e' key exists";
?>
The isset() function doesn't return true for array keys that were set together with null as its
value.
<?php
$vec = array('a','b','c','d','f','g','h');
if(in_array('a',$vec)) echo "<BR>'a' exists";
else echo "<BR>'a' doesn't exist";
if(in_array('b',$vec)) echo "<BR>'b' exists";
else echo "<BR>'b' doesn't exist";
if(in_array('c',$vec)) echo "<BR>'c' exists";
else echo "<BR>'c' doesn't exist";
if(in_array('d',$vec)) echo "<BR>'d' exists";
else echo "<BR>'d' doesn't exist";
if(in_array('e',$vec)) echo "<BR>'e' exists";
else echo "<BR>'e' doesn't exist";
?>
<?php
$vec_1 = array("a","b","c","d","f","g","h");
echo "<BR>before...<BR>";
var_dump($vec_1);
$vec_2 = array_flip($vec_1);
echo "<BR>after...<BR>";
var_dump($vec_2);
?>
<?php
$vec_1 = array("a","b","c","d","f","g","h");
echo "<BR>before...<BR>";
var_dump($vec_1);
$vec_2 = array_reverse($vec_1);
echo "<BR>after...<BR>";
var_dump($vec_2);
?>
.
<?php
$vec = array("a","b","c","d","f","g","h");
reset($vec);
while(key($vec)!==null)
{
echo key($vec)." is the key and ".current($vec)." is the value<BR>";
next($vec);
}
?>
<?php
$vec = array('moshe','david','michael','mike');
foreach($vec as $value_var)
{
echo "<BR>$value_var";
}
?>
<?php
$values_vec =
array('moshe','david','michael','mike');
$keys_vec = array('mosh','dav','mich','mik');
$vec = array_combine($keys_vec,$values_vec);
print_r($vec);
?>
The array_walk() Function
The array_walk(array &$vec, callback $function) function goes over each one of the array's
elements and calls the function on each one of them.
The function should include two parameters. The first is the array's value and the second is the
array's key.
The array_walk has a third optional parameter ($user_data). If it is passed then it would be
passed as an argument to the function that is called on each one of the elements.
<?php
$cars = array("T" => "Toyota", "M" => "Mazda", "S" => "Suzuki", "Y" => "Yamaha");
function changearray(&$val, $key, $prefix)
{
$val = "$prefix: $val";
}
function printarray($itemvalue, $itemkey)
{
echo "$itemkey : $itemvalue<br>";
}
echo "before ...<BR>";
array_walk($cars, 'printarray');
array_walk($cars, 'changearray', 'car');
echo "after...<BR>";
array_walk($cars, 'printarray');
?>
Arrays Sorting
PHP core functions include various methods for sorting arrays.
Calling sort() destroys all keys and reassign new ones starting from zero. Calling asort() keeps
the keys unchanged.
<?php
$japan_cars =
array("T" => "Toyota", "M" => "Mazda", "S" => "Suzuki", "Y" => "Yamaha");
$usa_cars =
array("C" => "Chevrolet", "P" => "Pontiac", "C" => "Cryzler");
echo "<P>before ...<BR>";
var_dump($japan_cars);
echo "<BR>";
var_dump($usa_cars);
sort($japan_cars);
asort($usa_cars);
echo "<P>after...<BR>";
var_dump($japan_cars);
echo "<BR>";
var_dump($usa_cars);
?>
Both sort() and asort() allows passing a second optional parameter, that configures the
operation. This second optional parameter can be one of the following possibilities:
SOFT_REGULAR
This is the default. Sorting will be performed according to elements' values and
SORT_NUMERIC
Each element's value will be first converted into a numeric value. The sorting will
SORT_STRING
<?php
$vec = array(
"a"=>"foofoo",
"b"=>"gondola",
"c"=>"israel",
"h"=>"honduras",
"d"=>"greece");
var_dump($vec);
rsort($vec);
echo "<p>";
var_dump($vec);
?>
The ksort() and krsort() functions sort an array by its elements' keys.
The usort(array &$vec, callback $function) function sorts an array by its elements' values and
using a user defined comparison function.
<?php
class Student
{
private $id;
private $average;
private $name;
function __construct($idVal, $averageVal, $nameVal)
{
$this->id = $idVal;
$this->average = $averageVal;
$this->name = $nameVal;
}
public function getId()
{
return $this->id;
}
public function getAverage()
{
return $this->average;
}
public function getName()
{
return $this->name;
}
public function __toString()
{
return $this->getName () . " id=" . $this->getId () .
" average=" . $this->getAverage ();
}
}
$vec = [
new Student ( 123123, 98, "danidin" ),
new Student ( 523434, 88, "moshe" ),
new Student ( 456544, 92, "spiderman" ),
new Student ( 744565, 77, "superman" )
];
echo "<h2>before</h2>";
foreach ( $vec as $k => $v )
{
echo "<Br>$k => " . $v;
}
usort ( $vec, function ($a, $b)
{
echo "<br>comparing between ".$a->getName()." and ".$b->getName();
return $a->getId() - $b->getId();
} );
echo "<h2>after</h2>";
foreach ( $vec as $k => $v )
{
echo "<Br>$k => " . $v;
}
?>
<?php
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$vec = array(12,532,12,56322343,232,5,2,1,1,1,4, 2, 5, 6, 1);
usort($vec, "cmp");
foreach ($vec as $key => $value)
{
echo "$key: $value<BR>";
}
?>
<?php
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$vec = array(12,532,12,56322343,232,5,2,1,1,1,4, 2, 5, 6, 1);
usort($vec, "cmp");
foreach ($vec as $key => $value)
{
echo "$key: $value<BR>";
}
?>
Array Shuffle
Calling the shuffle() function will scramble arrays' elements in a randomize order.
Using the array_rand(array $input [, int $num_req ] ) function we can get randomized selected
elements from our array. The first parameter is our array. The second parameter is the number
of elements we request.
If we request one element only, array_rand() returns the key for the random element. If we
request more than one element, array_rand() returns an array of keys for the random elements.
<?php
$vec = array("a","b","c","d","f","g","h");
$random_keys = array_rand($vec,3);
echo $vec[$random_keys[0]];
echo "<BR>";
echo $vec[$random_keys[1]];
echo "<BR>";
echo $vec[$random_keys[2]];
echo "<BR>";
?>
Arrays as Stacks
The array_push() and array_pop() functions enable us to use an array as a stack.
This function pushes the passed values onto the end of the array. The array's length is
increased by the number of the passed variables. This functions returns the number of
elements, the array has.
This function returns the last value of the array and shorten its length by one.
Arrays as Sets
The array_intersect() function returns an array containing all the values of array1 that are
present in all other arrays. The keys are preserved.
array array_intersect ( array $array1 , array $array2
[, array $ ... ] )
<?php
$vecA = array("il"=>"israel","ru"=>"russia","fr"=>"france","jo"=>"jordan");
var_dump($vecA);
echo "<br/>";
$vecB = array("ill"=>"israel","ru"=>"russia","fr"=>"franc","jo"=>"jordan");
var_dump($vecB);
echo "<br/>";
$vecC = array_intersect($vecA,$vecB);
var_dump($vecC);
?>
$vec = [34,234,75,4];
<?php
$vec_a = [4,6,2,7];
$vec_b = ['a'=>'australia','b'=>'belgium','c'=>'canada'];
foreach($vec_a as $k=>$v)
{
echo " ".$k."=>".$v;
}
foreach($vec_b as $k=>$v)
{
echo " ".$k."=>".$v;
}
Array Dereferencing
As of PHP 5.5 we can develop a function that returns an array and use a call to that function as
if it was an array.
The ?? Operator
The ?? operator, that was introduced in PHP 7, is also known as the isset ternary operator, is a
shorthand notation for performing isset() checks in the ternary operator.
This new operator assists us with those cases in which we need to check whether the array we
work with has a specific key so we could use its value and if not, then another value will be used
instead.
$vec = ['a'=>'abba','b'=>'baba','m'=>'mama'];
//before PHP7
//$temp = isset($vec['d'])?$vec['d']:'default';
$temp = $vec['d']??'default';
echo "<h1>$temp</h1>";
Array Constants
PHP 5.6 added the possibility to define array constants using the const keyword. As of PHP 7
we can define array constants using the define() function.
<?php
define('IMAGE_TYPES', ['jpg', 'jpeg', 'png', 'gif']);
foreach(IMAGE_TYPES as $v) {
echo "<h2>".$v."</h2>";
}
echo "<h1>".IMAGE_TYPES[0]."</h1>";
?>
PHP FUNCTIONS
The real power of PHP comes from its functions.
PHP has more than 1000 built-in functions, and in addition you can create
your own custom functions.
Syntax
function functionName() {
code to be executed;
}
Note: A function name must start with a letter or an underscore. Function
names are NOT case-sensitive.
Tip: Give the function a name that reflects what the function does!
Example
<?php
function writeMsg() {
echo "Hello world!";
}
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When the
familyName() function is called, we also pass along a name (e.g. Jani), and the
name is used inside the function, which outputs several different first names,
but an equal last name:
Example
<?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");
?>
In PHP 7, type declarations were added. This gives us an option to specify the
expected data type when declaring a function, and by adding
the strict declaration, it will throw a "Fatal Error" if the data type mismatches.
In the following example we try to send both a number and a string to the
function without using strict:
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
?>
In the following example we try to send both a number and a string to the
function, but here we have added the strict declaration:
Example
<?php declare(strict_types=1); // strict requirement
Example
<?php declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Example
<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
To declare a type for the function return, add a colon ( : ) and the type right
before the opening curly ( { )bracket when declaring the function.
In the following example we specify the return type for the function:
Example
<?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 Functions
PHP functions are similar to other programming languages. A function is a piece of
code which takes one more input in the form of parameter and does some processing
and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in
functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you −
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}
</body>
</html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
</body>
</html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function printMe($param = NULL) {
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello() {
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
is used to aggregate a series of similar items together, arranging and dereferencing them in some specific way.
•Each member of the array index references a corresponding value and can be a simple numerical reference to the value’s position in the series, or it could have some direct correlation to the
value.
•PHP array does not need to declare how many elements that the array variable have.
print_r() function
short for print recursive. This takes an argument of any type and prints it out, which includes printing all its parts recursively.
var_dump()function
is same as the print_rfunction except that it prints additional information about the size and type of the values it discovers
print_r() and var_dump() functions are commonly used for debugging. The point of this of these functions is to help you visualize what’s going on with compound data structures like arrays
foreach()function
is a statement used to iterate or loop through the element in an array. With each loop, a foreachstatement moves to the next element in an array.
foreachstatement
$key The name of the variable where you want to store the key. (optional)
$value The name of the variable where you want to store the value
Examples
Arrays: Sorting
Functions
is a group of PHP statements that performs a specific task. Functions are designed to allow you to reuse the same code in different locations.
Predefined functions
functions that are built-in into PHP to perform some standard operations
Syntax
functionname(param){
Where
function –is the keyword used to declare a function
param–is the formal parameters of the function. Parameter must follow the rule of naming identifier.
is one that declared outside a function and is available to all parts of the program.
Local Variables
is declared inside a function and is only available within the function in which it is declared.
Static Variables
Output:
Output:
Output:
Output: