PHP Tutorial – PHP Function

PHP Tutorial – PHP Function

In this lesson we are going to learn how to create a function in PHP.

A function is a block of codes that performs a particular task which can be executed anywhere in the page

A function will be executed by a call to the function.

In PHP, there are more than 700 built-in functions.

Here is the syntax of creating a function in PHP:

function functionName()
{
code to be executed;
}

PHP function guidelines:

  • Give the function a name that reflects what the function does
  • The function name can start with a letter or underscore (not a number)

Here’s a basic example:

<?php
function greetings()
{
echo "Hi guys!.How you do’in?";
}
greetings();
?>

Result:

Hi guys!.How you do’in?

PHP functions with parameter

Parameters are just like variable that is included in a function to add more functionality.

Note: Parameters appear within the parentheses “()”. They are like normal PHP variable.

<?php
function greetings($fname,$lname){
    echo " Welcome ". $fname . " ". $lname ."!<br />";
}
greetings("Piolo","Algara");
greetings ("Sam","Ondoy");
greetings ("Rolan","Pascual");
?>

In our example we have created function greetings and we have to send string containing someone’s first name and last name or else the script will break.

Note: In our function we can make as many parameters as we want.

PHP functions that returns a value

In PHP we can also create a function that returns a value. The value can be anything; it can be an integer, string or an array. To let a function return a value, use the return statement.

Here is an example of a function that returns a string value:

<?php
function greetings($fname) {
        return "hello there $fname!"; 
}
echo greetings("Piolo");
?>

In our example the function returns our string value instead echoing it inside. We call the function and echo its value outside. The above code outputs “hello there Piolo!”

Here is an example of a function that returns an integer value:

<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "4 + 5 = " . add(4,5);
?>
, , , , , ,

Post navigation

One thought on “PHP Tutorial – PHP Function

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.