0% found this document useful (0 votes)
21 views117 pages

Unit III Updated

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)
21 views117 pages

Unit III Updated

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

UNIT III

• Working with Data


Form Elements

•When we develop a website or a web application, we often have


to create forms to take input from users, like a Login form or a
Registration form.

•Creating a form on the webpage is accomplished using HTML,


while PHP serves as a transport for those values from the webpage
to the server and then in further processing those values.

•PHP provides two superglobals $_GET and $_POST for collecting


form-data for processing.
How HTML Form Works

create a simple HTML form and try to understand how it works,


what are the different attributes available in the <form> tag .

Example

<html>
<body>
<form action="form-handler.php" method="POST">
Name: <input type="text" name="name"> <br/>
Email: <input type="text" name="email"> <br/>
<input type="submit">
</form>
</body>
</html>
In the <form> tag, we have two attributes, action and method

action: Using this attribute, we can specify the name of the file
which will collect and handle the form-data. In the example
above, we have provided name of a PHP file.

method: This attribute specify the means of sending the form-


data, whether it will be submitted via POST method or GET
method.
<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>
Welcome.php

<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo
$_POST["email"]; ?>

</body>
</html>
PHP Form Handling

The PHP superglobals $_GET and $_POST are used to collect form-
data.

$_GET
An associative array of variables passed to the current script via the HTTP GET method.

$_POST
An associative array of variables passed to the current script via the HTTP POST
method.
PHP Post Form

• Post request is widely used to submit form that have large amount of
data such as file upload, image upload, login form, registration form
etc.
• The data passed through post request is not visible on the URL
browser so it is secured. You can send large amount of data through
post request.
PHP form handling
PHP Form Handling

PHP $_POST

PHP $_POST is a PHP super global variable which is used to collect form
data after submitting an HTML form with method="post".
$_POST is also widely used to pass variables.

PHP $_GET

PHP $_GET is a PHP super global variable which is used to collect


form data after submitting an HTML form with method="get".
$_GET can also collect data sent in the URL.
GET vs. POST

Both GET and POST create an array (e.g. array( key1 => value1,
key2 => value2, key3 => value3, ...)).

This array holds key/value pairs, where keys are the names of the
form controls and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are
superglobals, which means that they are always accessible,
regardless of scope - and you can access them from any function,
class or file

$_GET is an array of variables passed to the current script via the


URL parameters.

$_POST is an array of variables passed to the current script via


the HTTP POST method.
When to use GET?

Information sent from a form with the GET method is visible to


everyone (all variable names and values are displayed in the
URL).

GET also has limits on the amount of information to send. The


limitation is about 2000 characters.

However, because the variables are displayed in the URL, it is


possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other


sensitive information!
When to use POST?

Information sent from a form with the POST method


is invisible to others (all names/values are embedded within
the body of the HTTP request) and has no limits on the amount
of information to send.

However, because the variables are not displayed in the URL, it


is not possible to bookmark the page.
Exercise:

<form action="welcome.php" method="get">


First name: <input type="text" name="fname">
</form>

<html>
<body>
Welcome <?php echo $_GET[“fname”];
?>
</body>
</html>
Exercise:

<form action="welcome.php" method="post">


First name: <input type="text" name="fname"> </form>

<html>
<body>
Welcome <?php echo $_POST[“fname”];
?>
</body>
</html>
FORM Handling with GET

If we specify the form method to be GET, then the form-data is sent to the server using
the HTTP GET method.
PHP Global Variables - Superglobals

Some predefined variables in PHP are "superglobals", which


means that they are always accessible, regardless of scope
- and you can access them from any function, class or file

The PHP superglobal variables are:

•$GLOBALS
•$_SERVER
•$_REQUEST
•$_POST
•$_GET
•$_FILES
•$_ENV
•$_COOKIE
•$_SESSION
PHP Global Variables - Superglobals

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.
<?php
$x = 75;
$y = 25;

function addition()
{
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

addition();
echo $z;
?>
PHP Global Variables - Superglobals

PHP $_SERVER
$_SERVER is a PHP super global variable which holds
information about headers, paths, and script locations.

<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
PHP Global Variables - Superglobals

PHP $_REQUEST
PHP $_REQUEST is a PHP super global variable which is used to
collect data after submitting an HTML form.

PHP $_POST
PHP $_POST is a PHP super global variable which is used to
collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.

PHP $_GET is a PHP super global variable which is used to


collect form data after submitting an HTML form with
method="get".
REQUEST Variable

PHP $_REQUEST is a PHP super global variable which is used to


collect data after submitting an HTML form.

The example code shows a form with an input field and a submit
button. When a user submits the data by clicking on "Submit", the
form data is sent to the file specified in the action attribute of the
<form> tag.
In this code, we point to this file itself for processing form data. Then, we can use the
super global variable $_REQUEST to collect the value of the input field.

<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 = htmlspecialchars($_REQUEST['fname']);
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
FORM Handling Example
we will create a simple HTML form with different types of inputs and then write PHP code
for processing the form-data when submitted.

HTML FORM
<html>
<body>
<form action="form-handler.php" method="POST">
Name: <input type="text" name="name"> <br/>
Email: <input type="text" name="email"> <br/>
About Me:<br/>
<textarea name="aboutme"></textarea> <br/>
Gender:
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="male"> Male
<br/>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
FORM Output
PHP Form Validation

The HTML form contains various input fields: required and optional text
fields, radio buttons, and a submit button:
PHP Form Validation
The validation rules for the form above are as follows:

Field Validation Rules

Name Required. + Must only contain letters and whitespace

E-mail Required. + Must contain a valid email address (with @


and .)

Website Optional. If present, it must contain a valid URL

Comment Optional. Multi-line input field (textarea)

Gender Required. Must select one


PHP Form Validation

Text Fields

The name, email, and website fields are text input elements, and the
comment field is a textarea.

The HTML code looks like this:

Name: <input type="text" name="name">


E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
PHP Form Validation

Radio Buttons

The gender fields are radio buttons and the HTML code looks like
this:
Gender:

<input type="radio" name="gender" value="female">Female


<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
PHP Form Validation

The Form Element

The HTML code of the form looks like this:

<form method="post" action="<?php echo htmlspecialchars


($_SERVER["PHP_SELF"]);?>">

When the form is submitted, the form data is sent with method="post".

What is the $_SERVER["PHP_SELF"] variable?

The $_SERVER["PHP_SELF"] is a super global variable that returns the


filename of the currently executing script.
PHP Form Validation

The htmlspecialchars() function converts some predefined characters to


HTML entities.

The predefined characters are:


•& (ampersand) becomes &amp;
•" (double quote) becomes &quot;
•' (single quote) becomes &#039;
•< (less than) becomes &lt;
•> (greater than) becomes &gt;
PHP explode() Function

Definition and Usage

The explode() function breaks a string into an array.

Note: The "separator" parameter cannot be an empty string.


Note: This function is binary-safe.
Syntax

explode(separator,string,limit)

Parameter Description
separator Required. Specifies where to break the string
string Required. The string to split
limit Optional. Specifies the number of array elements to
return.
PHP Functions
PHP has more than 1000 built-in functions, and in
addition you can create your own custom functions.

PHP Built-in Functions

PHP has over 1000 built-in functions that can be called


directly, from within a script, to perform a specific task.
PHP Functions

PHP User Defined Functions

Besides the built-in PHP functions, it is possible to


create your own functions.

•A function is a block of statements that can be used


repeatedly in a program.

•A function will not execute automatically when a


page loads.

•A function will be executed by a call to the function.


PHP Functions

Create a User Defined Function in PHP

A user-defined function declaration starts with the word function:

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.
PHP Functions

<?php
function writeMsg()
{
echo "Hello world!";
}

writeMsg();
?>

Hello world!
PHP Functions

PHP Function Arguments

Information can be passed to functions through


arguments. An argument is just like a variable.

Arguments are specified after the function name,


inside the parentheses.

We can add as many arguments as we want, just


separate them with a comma.
PHP Functions

<?php
function familyName($fname)
{
echo "$fname Refsnes.<br>";
}

familyName("Jani"); Jani Refsnes.


familyName("Hege"); Hege Refsnes.
Stale Refsnes.
familyName("Stale");
Kai Jim Refsnes.
familyName("Kai Jim"); Borge Refsnes.
familyName("Borge");
?>
PHP Functions

<?php
function familyName($fname, $year)
{
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege","1975");
familyName("Stale","1978");
familyName("Kai Jim","1983");
?>
Hege Refsnes. Born in 1975
Stale Refsnes. Born in 1978
Kai Jim Refsnes. Born in 1983
String Functions
Strings
Strings in PHP are also a collection of alphanumeric characters, enclosed in single
quotes for simple string data and double quotes for complex string data.

<?php
$srt1 = "This is a String";
$str2 = 'This is also a String';
?>

We can define a string using double quotes as well as single quotes.

<?php
// string inside double quotes, with a single quote
$srt1 = "This is 'a' String";
// string inside single quotes, with a double quote
$str2 = 'This is also "a" String';
?>
String Functions
Example Code

<?php
// escaping double quote using backslash
$srt1 = "I\"ll handle this.";
// escaping single quote using backslash
$str2 = 'I\'ll handle this.';
echo $str1;
echo "\n"; // new line
echo $str2;
?>
String Functions
ord()

The ord() function returns the ASCII value of the first character
of a string.

Syntax
ord(string)

Parameter
String - The string to get an ASCII value from.

Return
The ord() function returns an integer between 0 and 255 that
would be the ASCII value of the first character of a string.
String Functions

Example
<?php
echo ord("h")."<br>"; //104
echo ord("hello")."<br>"; //104
?>

<?php
echo ord("welcome"); //119
?>
String Functions

Chr () function

The chr() function is used to get a single character string


from the specified ASCII value.
Syntax
chr(ascii)
Parameter
ascii - Specify the ASCII value
Return
The chr() function returns the character of the ASCII
value passed.
String Functions

<?php
$val = 119;
echo chr($val);
?>

OUTPUT
w
String Functions
PHP ltrim() Function
Remove characters from the left side of a string:

ltrim(string,charlist)

<?php
$str = "Hello World!";
echo $str . "<br>";
echo ltrim($str,"Hello");
?>
Hello World!
World!
String Functions
PHP rtrim() Function

Remove characters from the right side of a string:

<?php
$str = "Hello World!";
echo $str . "<br>";
echo rtrim($str,"World!");
?>

Hello World!
Hello
String Functions
Definition and Usage
The rtrim() function removes whitespace or other predefined
characters from the right side of a string.

Related functions:

•ltrim() - Removes whitespace or other predefined characters from


the left side of a string

•rtrim() - Removes whitespace or other predefined characters from


both sides of a string
String Functions

Remove whitespaces from the right side of a string:

<?php
$str = "Hello World! ";
echo "Without rtrim: " . $str;
echo "<br>";
echo "With rtrim: " . rtrim($str);
?>

The browser output of the code above will be:

Without rtrim: Hello World!


With rtrim: Hello World!
String Functions
substr() function in PHP
The substr() function is used to return a part of a string.

substr(string,start,length)
String Functions
Parameter Description

string Required. Specifies the string to return a part of

start •Required. Specifies where to start in the stringA positive


number - Start at a specified position in the string
•A negative number - Start at a specified position from the end
of the string
•0 - Start at the first character in string
length •Optional. Specifies the length of the returned string. Default is
to the end of the string.A positive number - The length to be
returned from the start parameter
•Negative number - The length to be returned from the end of
the string
•If the length parameter is 0, NULL, or FALSE - it return an
empty string
String Functions
<?php
// Positive numbers:
echo substr("Hello world",10)."<br>";
d
echo substr("Hello world",1)."<br>";
ello world
echo substr("Hello world",3)."<br>";
lo world
echo substr("Hello world",7)."<br>";
orld
echo "<br>";
d
// Negative numbers:
ello world
echo substr("Hello world",-1)."<br>";
lo world
echo substr("Hello world",-10)."<br>";
orld
echo substr("Hello world",-8)."<br>";
echo substr("Hello world",-4)."<br>";
?>
String Functions

<?php
// Positive numbers:
echo substr("Hello world",0,10)."<br>"; Hello worl
echo substr("Hello world",1,8)."<br>"; ello wor
echo substr("Hello world",0,5)."<br>"; Hello
echo substr("Hello world",6,6)."<br>"; world
echo "<br>";
Hello worl
ello wor
// Negative numbers:
Hello
echo substr("Hello world",0,-1)."<br>";
echo substr("Hello world",-10,-2)."<br>";
echo substr("Hello world",0,-6)."<br>";
?>
String Functions
PHP strcmp() Function

strcmp(string1,string2)

Definition and Usage

The strcmp() function compares two strings.

Note: The strcmp() function is binary-safe and case-sensitive.


Tip: This function is similar to the strncmp() function, with the
difference that you can specify the number of characters from
each string to be used in the comparison with strncmp().
String Functions
Paramet Description
er
string1 Required. Specifies the first string to
compare
string2 Required. Specifies the second string to
compare
String Functions

<?php
echo strcmp("Hello world!","Hello world!");
?>

If this function returns 0, the two strings are equal.


String Functions
Return •This function returns:0 - if the two strings are equal
Value: •<0 - if string1 is less than string2
•>0 - if string1 is greater than string2

<?php
echo strcmp("Hello","Hello");
echo "<br>";
echo strcmp("Hello","hELLo");
?>
0
-32
String Functions

<?php
echo strcmp("Hello world!","Hello world!")."<br>"; // the two
strings are equal
echo strcmp("Hello world!","Hello")."<br>"; // string1 is greater
than string2
echo strcmp("Hello world!","Hello world! Hello!")."<br>"; //
string1 is less than string2
?>

0
7
-7
PHP Math Functions
PHP abs() Function

The abs() function returns the absolute (positive) value of a number.

abs(number);

Parameter Description

number Required. Specifies a number. If the number is of type float,


the return type is also float, otherwise it is integer
PHP Math Functions
PHP abs() Function

<?php
echo(abs(6.7) . "<br>");
echo(abs(-6.7) . "<br>");
echo(abs(-3) . "<br>");
echo(abs(3));
?>

OUTPUT
6.7
6.7
3
3
PHP Math Functions

PHP ceil() Function

The ceil() function rounds a number UP to the nearest integer, if


necessary.

Tip: To round a number DOWN to the nearest integer, look at


the floor() function.

Tip: To round a floating-point number, look at the round() function.

ceil(number);

Parameter Description

number Required. Specifies the value to round up


PHP Math Functions

PHP ceil() Function


<?php
echo(ceil(0.60) . "<br>");
echo(ceil(0.40) . "<br>");
echo(ceil(5) . "<br>");
echo(ceil(5.1) . "<br>");
echo(ceil(-5.1) . "<br>");
echo(ceil(-5.9));
?>
1
1
5
6
-5
-5
PHP Math Functions
PHP floor() Function

The floor() function rounds a number DOWN to the nearest


integer, if necessary, and returns the result.

Tip: To round a number UP to the nearest integer, look at


the ceil() function.

Tip: To round a floating-point number, look at


the round() function.

floor(number);

Parameter Description
number Required. Specifies the number to round down
PHP Math Functions
PHP floor() Function

<?php
echo(floor(0.60) . "<br>");
echo(floor(0.40) . "<br>");
echo(floor(5) . "<br>");
echo(floor(5.1) . "<br>");
echo(floor(-5.1) . "<br>");
echo(floor(-5.9));
?> 0
0
5
5
-6
-6
PHP Math Functions
PHP round() Function

The round() function rounds a floating-point number.

Tip: To round a number UP to the nearest integer, look at


the ceil() function.

Tip: To round a number DOWN to the nearest integer, look at


the floor() function.

round(number,precision,mode);
PHP Math Functions
PHP round() Function
round(number,precision,mode);

Parameter Description
number Required. Specifies the value to round
precision Optional. Specifies the number of decimal digits to round to.
Default is 0
mode •Optional. Specifies a constant to specify the rounding
mode:PHP_ROUND_HALF_UP - Default. Rounds number up
to precision decimal, when it is half way there. Rounds 1.5 to 2
and -1.5 to -2
•PHP_ROUND_HALF_DOWN - Round number down
to precision decimal places, when it is half way there. Rounds
1.5 to 1 and -1.5 to -1
•PHP_ROUND_HALF_EVEN -
Round number to precision decimal places towards the next
even value
•PHP_ROUND_HALF_ODD - Round number to precision decimal
places towards the next odd value
PHP Math Functions
PHP round() Function
<?php
echo(round(0.60) . "<br>");
echo(round(0.50) . "<br>");
echo(round(0.49) . "<br>");
echo(round(-4.40) . "<br>");
echo(round(-4.60));
?>
1
1
0
-4
-5
PHP Math Functions

PHP fmod() Function

The fmod() function returns the remainder (modulo) of x/y.

fmod(x,y);

Parameter Description

x Required. Specifies the dividend

y Required. Specifies the divisor


PHP Math Functions

PHP fmod() Function

<?php
echo(fmod(20, 4) . "<br>");
echo(fmod(20, 3) . "<br>");
echo(fmod(15, 6) . "<br>");
echo(fmod(-10, 3) . "<br>");
echo(fmod(0, 0));
?> 0
2
3
-1
NAN
PHP Math Functions
PHP min() Function

The min() function returns the lowest value in an array, or the lowest
value of several specified values.

min(array_values);

or

min(value1,value2,...);

Parameter Description
array_values Required. Specifies an array containing the values
value1,value2,. Required. Specifies the values to compare (must be at least two
.. values)
PHP Math Functions
PHP min() Function

<?php
echo(min(2,4,6,8,10) . "<br>");
echo(min(22,14,68,18,15) .
"<br>");
echo(min(array(4,6,8,10)) . "<br>");
echo(min(array(44,16,81,12)));
?>
2
14
4
12
PHP Math Functions
PHP max() Function

The max() function returns the highest value in an array, or


the highest value of several specified values.

max(array_values);

or

max(value1,value2,...);

Parameter Description
array_values Required. Specifies an array containing the values
value1,value2 Required. Specifies the values to compare (must be at least
,... two values)
PHP Math Functions
PHP max() Function

<?php
echo(max(2,4,6,8,10) . "<br>");
echo(max(22,14,68,18,15) . "<br>");
echo(max(array(4,6,8,10)) . "<br>");
echo(max(array(44,16,81,12)));
?>
10
68
10
81
PHP Math Functions
PHP pow() Function

The pow() function returns x raised to the power of y.

pow(x,y);

x Required. Specifies the base to use

y Required. Specifies the exponent


PHP Math Functions
PHP pow() Function

<?php
echo(pow(2,4) . "<br>");
echo(pow(-2,4) . "<br>");
echo(pow(-2,-4) . "<br>");
echo(pow(-2,-3.2));
?>
16
16
0.0625
NAN
PHP Math Functions
PHP sqrt() Function

The sqrt() function returns the square root of a number.

sqrt(number);

Parameter Description

number Required. Specifies a number


PHP Math Functions
PHP sqrt() Function

<?php
echo(sqrt(0) . "<br>");
echo(sqrt(1) . "<br>");
echo(sqrt(9) . "<br>");
echo(sqrt(0.64) . "<br>");
echo(sqrt(-9));
?> 0
1
3
0.8
NAN
PHP Math Functions
PHP rand() Function

The rand() function generates a random integer.

Tip: If you want a random integer between 10 and 100 (inclusive), use
rand (10,100).

Tip: The mt_rand() function produces a better random value, and is 4


times faster than rand().

rand(); Parameter Description


min Optional. Specifies the lowest number to be
or returned. Default is 0
max Optional. Specifies the highest number to be
rand(min,max); returned. Default is getrandmax()
PHP Math Functions
PHP rand() Function

<?php
echo(rand() . "<br>");
echo(rand() . "<br>");
echo(rand(10,100));
?>

512549293
1132363175
79
PHP Array Functions

• Array()
• Count()
• list()
• in_array()
• current()
• Sort()
• each()
• next()
• Previous()
• rsort()
PHP list() Function
The list() function is used to assign values to a list of variables in
one operation.

list(var1, var2, ...)

Parameter Description

var1 Required. The first variable to assign a value to

var2,... Optional. More variables to assign values to


PHP list() Function

<?php
$my_array = array("Dog","Cat","Horse");

list($a, $b, $c) = $my_array;


echo "I have several animals, a $a, a $b and a $c.";
?>

I have several animals, a Dog, a Cat and a Horse.


PHP in_array() Function
The in_array() function searches an array for a specific
value.

in_array(search, array, type)

Parameter Description
search Required. Specifies the what to search for
array Required. Specifies the array to search
type Optional. If this parameter is set to TRUE, the
in_array() function searches for the search-string
and specific type in the array.
PHP in_array() Function
<?php
$people = array("Peter", "Joe", "Glenn",
"Cleveland");

if (in_array("Glenn", $people))
{
echo "Match found"; Match found
}
else
{
echo "Match not found";
}
?>
PHP current() Function
The current() function returns the value of the current element in
an array.

Every array has an internal pointer to its "current" element, which


is initialized to the first element inserted into the array.

current(array)

Paramet Description
er
array Required. Specifies the array to use
PHP current() Function

<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");

echo current($people) . "<br>";


?>

Peter
PHP next() Function

The next() function moves the internal pointer to, and outputs,
the next element in the array.

next(array)

Paramet Description
er
array Required. Specifies the array to use
PHP next() Function

<?php
$people = array("Peter", "Joe", "Glenn",
"Cleveland");

echo current($people) . "<br>";


echo next($people);
?>

Peter
Joe
PHP prev() Function
The prev() function moves the internal pointer to, and outputs,
the previous element in the array.

prev(array)

Parameter Description

array Required. Specifies the array to use


PHP prev() Function

<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");

echo current($people) . "<br>";


echo next($people) . "<br>";
echo prev($people);
?>

Peter
Joe
Peter
PHP end() Function

The end() function moves the internal pointer to, and outputs,
the last element in the array.

end(array)

Parameter Description
array Required. Specifies the array to use
PHP end() Function

<?php
$people = array("Peter", "Joe", "Glenn",
"Cleveland");

echo current($people) . "<br>";


echo end($people);
?>

Peter
Cleveland
PHP each() Function
The each() function returns the current element key and value, and
moves the internal pointer forward.

each(array)

Parameter Description
array Required. Specifies the array to use
PHP each() Function

<?php
$people = array("Peter", "Joe", "Glenn",
"Cleveland");
print_r (each($people));
?>

Array ( [1] => Peter [value] => Peter [0] => 0 [key] => 0 )
PHP rsort() Function

The rsort() function sorts an indexed array in descending order.

rsort(array, sorttype)

array Required. Specifies the array to sort


sorttype •Optional. Specifies how to compare the array
elements/items. Possible values:0 =
SORT_REGULAR - Default. Compare items
normally (don't change types)
•1 = SORT_NUMERIC - Compare items
numerically
•2 = SORT_STRING - Compare items as strings
PHP rsort() Function

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

Volvo
Toyota
BMW
PHP User Defined Function

• In all programming and scripting language, a function is a block of

statements that can be used repeatedly in a program.

• In PHP, the concept of the function is the same as in another language like

'C'. There are more than 1,000 in-built functions into the standard PHP

distribution.

• Besides these, we can define functions as per our requirements. These are

called 'User Defined Function'.


PHP User Defined Function

Syntax:

function function-name()
{
statement 1 :
statement 2 :
statement 3 :
......
}
PHP User Defined Function

Elements of a function

function: A function declaration starts with the special word 'function’.

Name of the function:

• The function name is defined by the user.


• A valid function name starts with a letter or underscore, followed by
any number of letters, numbers, or underscores.
• Remember that function names are case-insensitive.
PHP User Defined Function

Opening and Closing curly braces ({ } )

• The function body enclosed within a pair of braces which may contain
variable names an actual function code.
• The opening curly brace ( { ) indicates the beginning of the function
code and the closing curly ( } ) brace indicates the termination of the
function.
PHP User Defined Function

<?php
function myfunction()
{
echo "Good Morning";
}
myfunction();
?>

When we call the above function it will print Good Morning


PHP User Defined Function

Example: Functions within functions

<?php
function function1()
{
function function2()
{
echo "Good Morning <br>";
}
}
function1();
function2();
?>
PHP User Defined Function

Advantages of User-defined Functions


1.Reusable Code: you write a function once and can use it for a thousand times
in your program.
2.Less Code Repetition: we just have one line of code in the function, but what
if we have 10 lines of code. So rather than repeating all those lines of code over
and over again, we can just create a function for them and simply call the
function.
3.Easy to Understand: Using functions in your program, makes the code more
readable and easy to understand.
var_dump function

The var_dump() function dumps information about one or more


variables. The information holds type and value of the variable(s).

Syntax

•var_dump(var1, var2, ...);


parameter
var1,var2.... - Specifies the variable(s) to dump information
var_dump function

You might also like