PHP tutorial-Function

PHP Function


A function is a block of code to accomplish a specific task. A function is executed when it is called. A function returns or does not return a value;

A function that does not return a value

The following syntax can be used to define a function that deos not return a value.


function function_name(){
   statements;
}
 
Note: the name of function must start with a letter or underscore not a number.
Example:
<html>
<body>
 
<?php
//defining function:printHello
function printHello(){
 echo "Hello";
}
//calling the function:printHello
printHello();
 
?>
 
</body>
</html>

A function that returns a value

When you want to get the value generated from a function to be used elsewhere in your code, you will need to defind a function that can return a value. The return keyword is used to return the value of the function to another function or code block that calls it.


function function_name(){
   statements;
   return value;
}
 
Example:
<html>
<body>
 
<?php
//defining function: sum
function sum(){
  $s=10+20;
  return $s;
}
//calling the function: sum
$total=sum();
echo "Total=".$total;
 
?>
</body>
</html>
 

Function parameters


Parameters are values to be passed to the function. In the example below, a person' name is passed tothe printName function. You can pass more than one parameter to the function by separating them with comma.

Example:

<html>
<body>
 
<?php


//defining function:printName
function printName($name){
 echo "Hello ".$name;
}
//calling the function:printName
printName("Khorn Channa");
 
?>
 
</body>
</html>





Comments

Name:
Comment:
Enter the text:
CAPTCHA image

...........................................................................................................Home | Forum | About | Contact
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word.
However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.
Copyright @ 2011-2013 worldbestlearningcenter. All Rights Reserved.
Home Programming Web DB & App Questions Exercises Tips Programs FAQs Download About
Computer-Wbest
Web Scripts Tips
Download