Functions In PHP
A PHP function is a piece of code that can be reused multiple times. It can take input as argument list and return value. PHP has thousands of built-in functions.
Advantages of functions :
1. Reduce code redundancy
2. Increase reuse
3. Easy to maintain.
PHP provides huge set of built-in/core functions. PHP supports anonymous functions. Arguments to functions can be passed by value or reference.
Built-In functions
Function | Use | Syntax |
---|---|---|
print() | Same as echo statement | print ("This is sample output"); |
die() | An exit function alias. Used to terminate script and prints user message before exit | Perform_Action() or die("My Action failed"); |
header() | To add raw HTTP headers to send to the client browser | header("Location:http://www.letsfindcourse.com"); |
phpinfo() | Gives PHP interpreter settings bound to web server as a webpage. Useful in debugging/trouble shooting PHP settings | phpinfo() |
exit() | Common function to terminate a script | exit(); or exit; |
Variable Functions :
Function | Use | Syntax |
---|---|---|
isset() | Checks whether variable is declared and assigned a value and returns TRUE if set | echo isset($x); #FALSE |
unset() | A previously set variable is unset and releases memory allocated. Returns false, if variable is not already set | $x=10; => unset($x); => echo isset($x); => #FALSE |
empty() | Gives TRUE if variable is not declared or its value is FALSE or empty values | $x; => echo empty($x); => #TRUE |
User Defined Functions
#Syntax function function_name(Arguments){ // function body } #Example function caption(){ echo "Education and Research"; } //invoking caption();
Pass by value
#Example function net_pay($salary, $tax){ $taxable=$salary*$tax/100.0; $salary=$salary-$taxable; echo "Net amount : $salary"; #Net amount : 16000 } $sal=20000; $tax_per=20; net_pay($sal,$tax_per); echo "Salary : $sal"; #Salary : 2000
Pass by reference
#Example function net_pay(&$salary, &$tax){ $taxable=$salary*$tax/100.0; $salary=$salary-$taxable; echo "Net amount : $salary"; # Net amount : 16000 } $sal=20000; $tax_per=20; net_pay($sal,$tax_per); echo "Salary : $sal"; # Salary : 16000
Default argument
#Example function net_pay($salary, $tax =10){ $taxable=$salary*$tax/100.0; $salary=$salary-$taxable; echo "Net amount : $salary"; } //invoking the function: $sal=20000; $tax_per=20; net_pay($sal,$tax_per); # Net amount : 16000 net_pay($sal); # Net amount : 18000