PHP Functions


PHP Functions:– In addition to the built-in functions, PHP also allows you to define your own functions.When a php script finds a function call ; then immediately controls jumps into block of function and starts execution of block and control leaves it’s block only when it completes al statement’s execution.


PHP Functions | Example

Functions are “self contained” modules of code that accomplish a specific task.

Functions usually “take in” data, process it, and “return” a result.

Why do we use Functions in PHP

They allow us to reuse code instead of rewriting it.

Functions allow us to test small parts of our program in isolation from the rest

Functions can be reused in other php application using include keyword.

Example

<?php

function fun(){
	
	echo "hello php";
	echo "<br>";
	echo "<br>";

}
 function days_name($day_name){
	 
	echo "First day of Week is ".$day_name ; 
	 
 }
 
 function employee($name,$city){
	
    echo $name." lives in ".$city;	

 }
 
 function temp_today($temprature=20){
	 
	 echo "Today's Temperature is " . $temprature;
 }
 
 fun();//Zero Argument 
 
 days_name("Sunday");//One Argument 
 echo "<br>";
 echo "<br>";
 employee("Harish","Delhi");//Two Argument
 echo "<br>";
 echo "<br>";
 temp_today();
 
 
?>

Returning Values from Functions | Example

Example

<?php

function addition($a,$b){
	$z=$a+$b;
	return $z;
}
 
 echo "10 +20=" .addition(10,20)."<br>";
 echo "5 +5=".addition(5,5)."<br>";
?>

Passing Arguments to a Function by Reference

When we pass a value by address in function as a parameter; it’s value will get changed outside the function.If you do not want any change into your variable then pass it by value as parameter in your function’s argument.

Example

<?php
function addition(&$number){
	$number*=$number;
	echo $number;
	echo "<br>";
	return $number;	
}

$value=10;
echo $value;
echo "<br>";
echo addition($value);
echo "<br>";
echo $value;
?>

Advertisements

Add Comment

đź“– Read More