Hello friends, this is my 9th tutorial of PHP and Today I am sharing the concept of using functions in PHP. Functions are block of codes that performs specific operations. Functions are useful as they help to make a code modular and more structure.
Creating function with no argument and no return type :
 <?php 
function show() {
 echo "Show is called";
}
show();
?>
Creating function with argument but no return type :
 <?php 
function sum($a,$b) {
 $c=$a+$b;
 echo "Sum is : {$c} ";
}
sum(10,20);
?>
Creating function with argument and return type :
 <?php 
echo mul(2,3);
function mul($a,$b) {
 $c=$a*$b;
 return $c;
}
?>
Creating function that returns multiple values :
 <?php 
function sum_diff($a,$b) {
 $c=$a+$b;
 $d=$a-$b;
 $result=array($c,$d);
 return $result;
}
$res=sum_diff(50,30);
echo "Sum : {$res[0]} ";
echo "Difference : {$res[1]}";
?>
Using global variables inside a function :
 <?php 
$b="Outside";
function glo_change() {
  global $b;
  $b="Local";
}
glo_change();
echo $b;
?>
Using default parameter inside a function :
 <?php 
function paint($color="red") {
  echo "Color of the room is {$color}";
}
paint("blue");
paint();
?>

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.