In any programming language, when we need to do the same task again and again, we should use the concept of Reusability, to make this task easier.
Functions are the key to reuse the code. Function is a set of statements that we can execute, whenever we require. It can be performed by invoking the function by name. When we use functions in our code, basically we have to follow call return mechanism for that. It means that in using functions we should follow the steps:
- Calling the function by passing some arguments.
- After the calling control will move to the function definition and then the set of statements written inside the function block are get executed.
- After the execution of function, control will return to the module, from where the function was called.
Functions can be of two types in PHP:
1. In built functions
The functions which are predefined and we can use these functions directly according to the syntax of function are called in-built functions.
These functions are further can be of various types, such as:
- Date and time functions
- String functions
2. User defined functions
A used cal also declare functions according to their requirements, these are called user defined functions.
Declaration of function
In PHP function declaration syntax is:
function <function_name>(arg1, arg2, arg3,......argn) { //set of statements }
Here function is the key word used to declare function. Function name must follow the same rules as variable naming conventions. Like it must begin with a letter or an underscore, rest of the characters may be letters, numbers or underscore.
Example:
<?php function page_header() { echo '<html><head><title> Welcome to the world of PHP</title></head>'; echo '<body bgcolor="violet"><H1> WELCOME TO THE PHP TUTORIALS</H1>'; } page_header(); //function call echo '<br>'; echo "<h3>Welcome!!!!!!!!!</h3>"; page_footer(); //function call function page_footer() { echo '<hr><h4> Thanks for Visiting!!!!</h4>'; echo '</body></html>'; } ?>
The output of above code is:
We can pass parameters in functions and a function can return value also.
<?php function Check_even($number) { if($number%2==0) return 1; else return 0; } $number=27; $result=Check_even($number); if($result==1) echo "Number is even"; else echo "Number is odd"; ?>
The output of above code is:
Variable Scope
In PHP, variables in function can be used to pass values and return values from functions. On the basis of variables accessibility (scope of variables), variables can be classified in two types:
Global variables
When variables are declared outside the function body, they can be accessed in all the functions of a program or script. This is called global declaration of variables.
Local variables
When variables are declared inside the function body, they can’t be accessed through other functions; it is called local variable declaration.
<?php $language1='PHP language'; //global variable function display() { $language2='phython'; //local variable echo "We are working on : $language1"; echo "<br>"; echo "In web developement $language2 is also widely used"; } echo $language1; echo "<br>"; echo $language2; //it will give error "Undefined variable:language2" ?>
Output of above code is:
Default arguments in functions
Default arguments can be used in PHP, when we want to call function with same default parameters in case user doesn’t pass those parameters at the time of function call.
<?php function myFunction($number=5) { for($i=1;$i<=10;$i++) { echo "$number"."x"."$i=".$number*$i; echo "<br/>"; } } echo "First 10 multiples"; echo "<br/>"; echo "function call with default parameter"; echo "<br/>"; myFunction(); echo "function call with passed argument"; echo "<br/>"; myFunction(7); ?>
The output of above code is:
Predefined functions in PHP
In PHP there are number of predefined functions are available for various categories like:
- Array functions: already discussed in array chapter
- Date and time functions:
- Math functions:
- String functions:
- Class/object handling functions
- Directory and file functions
- Error handling functions
- HTTP functions
- Image functions
- Mail functions
- Database functions
- Other functions
Date or time functions
The date() and strftime() functions
<?php echo 'Displaying current date and time using inbulit functions in PHP'; echo "<br/>"; echo "Using strftime() function:<br/>"; echo strftime('%c'); echo "<br/>" ; echo "<br/>" ; echo "Using date function:<br/>"; echo date('r'); ?>
The output of above code will be:
By default date() and strftime() both functions display date and time in mm/dd/yy hh:mm:ss format. We can also change the format if needed by passing parameters in these functions as follows:
<?php echo 'Displaying current date and time using inbulit functions in PHP'; echo "<br/>"; echo "Using strftime() function:<br/>"; echo strftime('%c'); echo "<br/>" ; echo "<br/>" ; echo "Using date function:<br/>"; echo date('r'); echo "<br/>Date format change<br/>"; // date function will take parameter 'd/m/y' as follows echo "Using date function<br/>"; echo date('d/m/y'); // strftime function will take parameter '%d/%m/%y' as follows echo "<br/>"; echo "Using strftime function<br/>"; echo strftime('%d/%m/%y'); ?>
The output of above code will be:
strtotime()
This function is used to convert a string into specific date format.
<html> <header> </header> <body> <?php $startdate=strtotime("Sunday"); $enddate=strtotime("+7 days",$startdate); echo "schedule for next week<br/>"; while ($startdate < $enddate) { echo date("M d", $startdate),"<br>"; $startdate = strtotime("+1 day", $startdate); } ?> </body> </html>
The output of above code is:
String functions in PHP
strlen()
This function takes one argument either literal string or string variable and returns the number of characters including white space in string.
<html> <p> <?php $lang="server side scripting language"; echo strlen($lang); ?> </p> </html>
The output of above code is:
substr()
This function can be used to extract a piece of string from another string. This function takes three parameters. First is the string from which we have to extract the substring, second parameter is the starting position from where we have to fetch the substring and third is the number of characters we have to fetch.
<html> <p> <?php $lang="server side scripting language"; echo substr($lang,0,6); ?> </p> </html>
Output of above code is:
strtoupper() and strtolower()
These functions are used to convert string from lowercase to uppercase and from uppercase to lowercase vice versa.
<?php $firstname="andrew"; $lastname="John"; echo strtoupper($firstname." ".$lastname); echo "<br/>"; echo "**********************************<br/>"; $lang="PHP SCRIPTING LANGUAGE"; echo strtolower($lang); ?>
The output of above code is:
strpos()
This function is used to find the first occurrence of substring in another string.
<?php $lang="This tutorial is based on PHP scripting language. PHP is server side scripting language."; $pos=strpos($lang,"PHP"); echo $lang; echo "<br/>"; echo "*******************************************<br/>"; echo "The first occurence of PHP string is".$pos; ?>
The output of above code is: