Passing Data to Function.................................................................................................................................................1
Passing Arrays to Functions............................................................................................................................................2
Passing by Reference.....................................................................................................................................................2
Using Default Arguments................................................................................................................................................3
Passing Variable Number of Arguments.........................................................................................................................3
Returning data from functions........................................................................................................................................4
Scope of a Variable.....................................................................................................................................................6
Accessing Global Data....................................................................................................................................................7
Working with Static Variables.........................................................................................................................................8
Creating Include Files...................................................................................................................................................10
Returning Errors from Functions..................................................................................................................................11
READING DATA IN WEB PAGES.................................................................................................................................12
Setting up Web Pages to Communicate with PHP........................................................................................................12
Handling Text Field.....................................................................................................................................................13
Handling Text Areas.....................................................................................................................................................13
Handling Radio Buttons................................................................................................................................................15
Handling List Boxes:....................................................................................................................................................16
Download PHP class notes-unit 2 and more Lecture notes Programming Languages in PDF only on Docsity!
Unit II
Creating Function..................................................................................................................................................... Table of Contents
Passing Data to Function.................................................................................................................................................
Passing Arrays to Functions............................................................................................................................................
Passing by Reference.....................................................................................................................................................
Using Default Arguments................................................................................................................................................
Passing Variable Number of Arguments.........................................................................................................................
Returning data from functions........................................................................................................................................
Scope of a Variable.....................................................................................................................................................
Accessing Global Data....................................................................................................................................................
Working with Static Variables.........................................................................................................................................
Creating Include Files...................................................................................................................................................
Returning Errors from Functions..................................................................................................................................
READING DATA IN WEB PAGES.................................................................................................................................
Setting up Web Pages to Communicate with PHP........................................................................................................
Handling Text Field.....................................................................................................................................................
Handling Text Areas.....................................................................................................................................................
Handling Radio Buttons................................................................................................................................................
Handling List Boxes:....................................................................................................................................................
Using Php’s Server Variable:........................................................................................................................................ 20 Using HTTP Headers.................................................................................................................................................... 21 Redirecting Browser with HTTP Headers.................................................................................................................... 22
Dumping a Form’s Data All at once..............................................................................................................................
Performing Data Validation...............................................................................................................................................
Checking for already visited page:................................................................................................................................ Requiring Numbers..................................................................................................................................................... 26 Requiring Text..................................................................................................................................................... 27 Persisting user data..................................................................................................................................................... 27 Client-Side Data Validation........................................................................................................................................... Handling html tags in user input................................................................................................................................... 29
Creating Function
Functions are callable section of code, where data’s are passed to it, and that can return data.
(^) Uses of function:
Code’s can be broken into small pieces.
Code’s can run multiple times in the application.
Function coding is not executed at page load.
Codes can be placed in a function that is too long to debug and maintain.
PHP functions support many unique features.
The variables used inside a function are, by default, not visible outside that function.
Creating Function
Syntax for creating function:
functionfunction_name ([arg_list…])
{
[statements]
[returnreturn_value]
}
E.g:
function display() { echo “Message from function”;
function average($arr) { $sum = 0; foreach($arr as $v) $sum += $v; echo "Average = " , $sum / 3; } ?> Output: Average = 70.
Passing by Reference.....................................................................................................................................................
When arguments are passed to function, a copy of the actual data is passed not the actual variable.
Therefore even if the value of that argument is changed in the function, the actual value doesn’t change.
(^) To pass the actual value to a function, the address of the variable is passed as argument,
With the address of the variable as argument, when the value is altered inside the function, it reflects outside the function also.
To pass the reference as function argument, a (&) ampersand symbol is included as preface to that argument in function definition. E.g: Program 2. <?php $n = 4; echo "Value in n = " , $n; square ($n); echo "Value in n after Function Call = " , $n; function square (&$no) { $no = $no * 2; } ?>
In the above program,
$n variable holds a value 4.
The value is then displayed.
Function square is called with $n as argument.
In the function definition, the argument name is prefaced with an & symbol.
Inside the function, $no variable is multiplied with 2.
Control returns to the main program.
Value of n is displayed again. The output is: Value in n = 4Value in n after Function Call = 8
Using Default Arguments
In PHP for a function with n arguments, it is possible to pass less than n arguments. Provided the arguments are assigned default values in the definition.
The default argument is added in the argument list using an equal sign. E.g. Program 2. <?php function display($g, $m = "welcome") { echo $g; echo $m; } display ("Hello");
With default arguments, if we don’t pass anything for the second argument, php compiler will assign the default argument automatically.
Default values can be given for more than one argument, but you have to give them to all arguments that follow as well, so that php won’t get confused, if more than one argument is missing.
Passing Variable Number of Arguments.........................................................................................................................
In php, a function can accept variable number of arguments i.e. the number of arguments in function definition varies from the number of arguments passed to it in function call.
Such arguments are handled using the following functions:
i. func_num_args () The function returns the number of arguments passed to it. ii. func_get_arg() Returns single arguments. iii. func_get_args() Returns all arguments in an array.
it gets the arguments passed to it in $a array using function “func_get_args()”
it combines all argument values and displays them as one string.
Outside the function, the same function is called with different number of arguments. The output of the program would be: Hello Welcome to all abc company’s
Returning data from functions........................................................................................................................................
To return data from functions the “return” keyword is used inside the function.
Syntax: return;
This added to a function definition, takes the control, to the calling function. Along with it some data’s are also transferred.
The function call statement is replaced with its return value E.g: Program 2. <?php function add($op1, $op2) { $sum = $op1 + $op2; return $sum ;
In the calling function, list () function is implemented to extract the array returned from the function. O/p: 0 3 6 0 3
The reference to a variable is gotten through the reference operator &. E.g. $v = 5; $x = & $v; - $x will contain the reference of variable $v. i.e. $x & $v point to the same data in memory. - Syntax for returning a reference to and from a function: function& (& argument) { statement; } ♦ The function takes a reference as its argument, as the & in the argument list indicates, and it also returns areference, as is indicated by the & in front of the function name. E.g. Program 2.
Output: Current value = 4 New value = 5 - In the above program, - The variable $v is assigned value 4 and is displayed accordingly - The address of variable $v is passed as argument to function “ref”. - Inside function “ref” the value is incremented b 1 and returned to the main program. - In the main program the value is $r is printed to show the change. - From the program it is understood that if the reference of the variable is included in any statement then the changed value is reflected in the variable also.
Scope of a Variable.....................................................................................................................................................
The variables created inside and outside the functions are independent of each other, even if they use the same name.
The scope of a variable is the region of code within which a variable is visible. Variable scoping helps avoid variable naming conflicts. E.g. Program 2. <?php $x = 5;$v=8; echo "Value in x = $x"; disp (); echo "Current value in x = $x"; echo "Value in v = $v"; function disp() {
$x = 10; echo "Value of X in function = $x"; echo "Value in V inside function = $v"; } ?>
Output: Value in x = 5 Value of x in function = 10 Error: undefined variable V in line 11 Current value in x = 5 Value in v = 8
In the above program,
A variable $x is defined in main program as well as function disp ().
The variable $x doesn’t conflict with each other.
Similarly the $v variable is defined in the main program. So it has scope in the main program only.
When $v is accessed in sub program without any references for it, Error will be raised saying “Undefined Variable”.
The value of a variable persists only in its block,. This is called scope of a variable.
Accessing Global Data....................................................................................................................................................
To access a variable outside its definition area, the variable should be declared globally.
Global data is also called as script – level data in php.
To access the data from a different script level, the keyword “global” is used.
Syntax: Global E.g. Program 2. <?php $v = 4; echo "$v In Main Program = $v"; scoper (); global_scoper(); echo " $v in main program again = $v"; function scoper() { $v = 8000; echo " $v in scoper function = $v"; } function global_scoper() { global $v; $v=7; echo " $v in global_scoper function = $v"; } ?> Output: $v in main program = 4 $v in scoper function = 8000 $v in global_scoper function = $v in main program again = 7
In the above program,
The variable $v in main program has value 4.
The $v in scoper () has 8000 as its value.
Whereas $v in global_scoper () has 4 initially and changed to 7, because the $v is assigned as global here.
The changed value is again reflected in main program.
$bool = TRUE;
echo "Conditional Function is not Ready";
cond_func();
if ($bool)
{
function cond_func()
{
echo " Msg from conditional function";
}
}
?>
Output:
Conditional Function is not Ready
Fatal error : Uncaught Error: Call to undefined function cnd_func()
In the above program, the cond_func () is not available until, the if-statement containing it executes; the result will be a FATAL error.
If a conditional program exists in the code, they should be called only after the conditional block
containing it is executed.
Change the function call from before the if statement to after the if-statement like below.
Eg:
Msg from conditional function"; } } cnd_func(); ?> Output:
Like variable variables, variable function can also be created in php.
The name of a function is assigned to a variable, and whenever the function is required, the function is accessed through its variable.
(^) E.g. Program 2.
function red($arg)
{
echo "Red = $arg" ;
}
$f_var = "red";
$f_var ("color");
?>
Output:
Red = color
In the above program,
The function “red” takes on a argument, and prints the argument’s value.
The name of the function is assigned to a variable.
The variable is called with an argument to the function.
$f_var (“color”);
This statement will assign the value red to the “$_var” part, and in turn the function red (“color”) is called and executed.
Being able to assign function will help to split up an extensive code in smaller parts.
Nesting function
Like nesting of looping statements nesting of function is also accepted in php.
The nested function won’t be accessible until the enclosing function has been run.
E.g. Program 2.
outer_function ();
inner_function();
Main program:
include("math.inc");
echo PI;
echo " Sum of 5 and 9 is " , add(5,9);
?>
Save this file as include.php
Running the “include.php”, the coding of “math.inc” are available to this program on encountering the statement include(“math.inc”).
Returning Errors from Functions..................................................................................................................................
Every function will return a FALSE, if there’s been an error.
This can be included in user_defined function using the die() function to print an error message.
Syntax:
or die(message);
(^) This function can be included to any statement. In case the statement returns an error, the die function is called.
This function will display the message passed as argument instead of the system developed error message.
E.g. Program 2.
echo "Reciprocal of 2 is:";
recep(2) or die("can't find reciprocal of zero");
echo "Reciprocal of 0 is ";
recep(0) or die(" can't find reciprocal of zero");
function recep($a)
{
if ($a !=0) {
echo (1/$a);
return TRUE; }
else
return FALSE;
}
?>
Output:
Reciprocal of 2 is:0.5Reciprocal of 0 is can't find reciprocal of zero
(^) In the above program,
The recep() function is called twice. When the argument is 0, the function is designed to return FALSE which will invoke the die() instead of giving warning.
E.g.
Reset button, when clicked, will reset the data in all the html controls in the form back to their default values.
To access the data on the server, $_POST array or $_GET array is used.
(^) If GET method is used, the data can be gotten from $_GET array.
If POST method is used, the data can be gotten from $_POST array.
$_REQUEST array holds both data’s from $_post and $_GET.
These are “Super_global” array used to transfer data from html to php.
Difference between $_POST array and $_GET array:
$_GET $_POST
The data sent with “get” method is always URL-encoded (Spaces are replaced with + signs, different controls name / data pairs are separated with an &), and placed into the URL.
Data’s are accessed through $_GET global array.
Book marked pages can be viewed without errors.
User data’s are not secure. E.g. www.php.net/? Uname = kris& pass = Bharath - The user data does not appear in the URL. The data is encoded such that only the server can decode the data. - The encoding differs for every hit. - Users send data through HTTP Headers. - Bok marked pages cannot be viewed in a later date. - Data’s are more secure. - Data’s are accessed through $_POST global array. - HTTP Headers send the data to the server. E.g. www.php.net/? 50ejklm790e…
Handling Text Field.....................................................................................................................................................
(^) A text field is added to the html program using the method with the type attribute set to “text”.
In php, the text data is accessed using the $_REQUEST or $_POST or $_GET array depending on how data’s are submitted to the form.
E.g. to load an input control.
<input type = “text” name = “txt1” value = “Enter name”>
The above coding will created a text field control and place it in the current form.
E.g. Program 2.
Php program:
$nm = $_REQUEST ['txt1'];
echo $nm;
?>
(^) In the above program,
A text field and a submit button is added to the form.
The data typed in the text field is sent to the server and process.php is called.
The php script gets the text in the text field through the $_REQUEST global array.
Handling Text Areas.....................................................................................................................................................
Text field can handle up to a length of 255 characters.
Text field will handle single line of text.
“Text areas” are controls that can handle multiple line of text input.
They can handle “\n” new line characters as well.
(^) To add Text Area Control to HTML, the following coding is used.
<text area name = “ cols = “” rows = “”>
</text area>
E.g. Program 2.
Php2-21.php:
echo "Reading data in Check boxes ";
if(isset($_POST['check1']))
echo $_POST['check1']," ";
if(isset($_POST['check2']))
echo $_POST['check2']," ";
if(isset($_POST['check3']))
echo $_POST['check3']," ";
?>
In the above program,
(^) 3 check boxes are added to the program.
When the submit button is pressed, all control data’s in-between are sent to the server.
Php form can access the data using appropriate super global arrays.
The values in check boxes can be printed directly like $_request [‘check1`] but if the user had not selected any of the check boxes means, there won’t be any data in the variable.
So before attempting to print a check box data, we have to check whether the check box has any value or not.
It is achieved using the isset () function.
A check box if selected will display the text present in its value attribute.
Handling Radio Buttons................................................................................................................................................
Radio button allows the user to select one out of many items in a group.
Application for Radio Button is selecting gender. It will be either male or female. Not both options can be selected.
Syntax E.g.:
The above coding will create a radio button with the name “rad1” and its value attribute is set to “yes”.
E.g. program 2-
Php coding: php2-22.php
?>
The above php coding will display the text in value attribute when the code runs.
But if no radio is selected, then there will be a NULL value, which will raise error.
Alter the above coding to view like below.
if (isset ($_REQUEST[‘radio1’]
{
echo $_REQUEST[‘radio1’];
}
?
In the above program,
The user will be allowed to choose either one of the radio button.
Because those two radio button has the same name.
Only one of the all options can be selected.
(^) If there is a need to add a separate set of radio buttons, they can be added with a different name, to group them separately.
In the php program,
The value in a radio button can be printed like any ordinary value. But if no radio is selected, the name will contain a NULL value.
Therefore first the name field is checked, whether it has any data or not, using isset(), then the value is used elsewhere accordingly.
Handling List Boxes:....................................................................................................................................................