Dreevoo.com | Online Learning and Knowledge Sharing
 
Home | Programs | Programming languages | PHP & MySQL | How to write and use PHP functions
Guest
Click to view your profile
Topics
Programs
Languages
Recipes
Home
Shortcuts
 
 

How to write and use PHP functions

Functions in PHP are a block of code that can be executed whenever we need it, without the need to write the same code again.

 
  Author: podtalje | Version: php.net | 24th April 2013 |  
 
 
1.
 

Definition of function is very simple.

<?php

function functionName($parameters) {
  //code that will be executed
}
?>

We start with the word function, we set an arbitrary name (in our case functionName) and specify the parameters.


 
 
2.
 

So let's write our first function.

<?php

function sum() {
  //code that will be executed
  echo 3+2;
}

sum();
?>


First we create the new function sum. The function does not need  parameters and will just output sum of values 3 and 2.

After that we can call the function from any place in our code with sum();

 
 
3.
 

Now we can make function more general by accepting two parameters so that function can calculate sum of arbitrary two numbers.

<?php

function sum($val1, $val2) {
  //code that will be executed
  echo $val1 + $val2;
}

sum(3,2);
?>


 
 
4.
 

When calling the function and instead of using fixed values, we can also use variables as parameters.

<?php

function sum($val1, $val2) {
  //code that will be executed
  echo $val1 + $val2;
}

$p1=3;
$p2=2;

sum($p1,$p2);

?>

Here we call the function with variables $val1 and $val2.

 
 
5.
 

Very important thing to know is that functions can also return values.

<?php

function sum($val1, $val2) {
  //code that will be executed
  $result = $val1 + $val2;
  return $result;
}

$p1=3;
$p2=2;

$res = sum($p1,$p2);
echo $res;
?>

Result is returned by using return statement at the end of the function.

We can then store the result of function into variable and use the result later in the code.

 
 
 
   
  Please login to post a comment
  Click to open user profile  
Shahbaz, 28th Sep 2013, 5:50 PM
Very Gooooooooooood that is i was searching in Google to Learn Basic. so manay thank sirSir i have a request can u please make more Tutorial on Function PleaseLike Add New User , update, Delete using Function instead hard code
 
 
  Click to open user profile  
podtalje, 28th Sep 2013, 6:09 PM
No problem, I can add more tutorials about PHP.

Today I will make one lesson about login system, which will show you how to handle login and registered users.

Of course if you have any additional questions or request for a specific lesson, just let me know.


 
 
  Click to open user profile  
podtalje, 30th Sep 2013, 2:24 AM
The lesson about simple login system can be found below

[z.lesson 1712]

If you need a new lesson for some other functionality just let me know.
 
   
 
 
online learning made for people
Dreevoo.com | CONTRIBUTE | FORUM | INFO