Sunday, 9 April 2017

php function with example

php functions with example
A user defined function declaration starts with the word "function":

Syntax
function functionName() {
code to be executed;
}
Note: A function name can start with a letter or underscore (not a number).

Tip: Give the function a name that reflects what the function does!

Note Function names are NOT case-sensitive.
In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of the function. The function outputs "Hello world!". To call the function, just write its name:

<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function
?>

Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name:

<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}

familyName("Janis");
familyName("Hedge");
familyName("Stadle");
familyName("Kait Jim");
familyName("Borgde");
?>

The following example has a function with two arguments ($fname and $year):

Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>

php function with argumemts

The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:

<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

php function with return

<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>

No comments:

Post a Comment

remove a property from a JavaScript object?

remove a property from a JavaScript object? delete myObject.regex; // or, delete myObject['regex']; // or, var prop = ...