saftutorials.com
PHP Functions Tutorial
PHP function is a set of instructions which perform some specific task just like another programming languages. 
PHP function does not run when the page load. 
PHP function receive one or more parameters and return some value i.e variable, array, object etc.
In PHP there are thousands pre-built functions like strpos(), fopen(), fread() etc.


PHP functions are divided into two parts

function definition

function call


Syntax of PHP function

function nameOfFunction() {

set of instructions;

...

...

}


Example of simple PHP function

<!DOCTYPE html>
<html>
<body>
<?php
// function definition
function sayHello() {
echo "Hello John !";
}
?>

<?php
// function call
sayHello();
?>

</body>
</html>


The above code produces the following results

Outputs: Hello John!


Example of PHP function with arguments

<!DOCTYPE html>
<html>
<body>
<?php
// function definition
function sayHello($name) {
echo "Hello ".$name;
}
?>

<?php
// function call
sayHello('Sam !');
?>

</body>
</html>

The above code produces the following results

Outputs: Hello Sam!


Example of PHP function with default argument

<!DOCTYPE html>
<html>
<body>
<?php
// function definition
function sayHello($name = 'John !') {
echo "Hello, ".$name."<br />";
}
?>

<?php
// function call
sayHello();
sayHello('Sam!');
sayHello('Rose!');
?>

</body>
</html>

The above code produce the following results

Outputs: Hello, John!

Hello, Sam!

Hello, Rose!


Example of PHP function with returning values

<!DOCTYPE html>
<html>
<body>
<?php
// function definition
function sayHello($name = 'John !') {
$abc = "Hello, ".$name."<br />";
return $abc;
}
?>
<?php
// function call
echo sayHello();
echo sayHello('Sam!');
echo sayHello('Rose!');
?>
</body>
</html>

The above code produces the following results

Outputs: Hello John!

Hello, Sam!

Hello, Rose!


Find us on

Facebook Google Plus Twitter Pinterest YouTube

web statistic