Filed under: PHP
PHP Functions
In this tutorial, i will teach you how to make functions in PHP and how to use it. A function is a block of code that we can call and use whenever we want.
Below is an example of a function that will display the text “learn PHP” when called:
<html>
<body>
<?php
function displayMessage()
{
echo “learn PHP.”;
}
displayMessage();
?>
</body>
</html>
Another example where we will be using the function we made:
<html>
<body>
<?php
function displayMessage()
{
echo “learn PHP.”;
}
echo “I want to “;
displayMessage();
?>
</body>
</html>
Output is:
I want to lean PHP
PHP Functions – Adding Parameters
We can also add parameter to our functions so it can have different outputs depending on the user input. A parameter is just like a variable. We should place the parameters inside the parentheses like this displayMessage($myMessage).
Here is an example where it will display our inputted message:
<html>
<body>
<?php
function displayMessage($myMessage)
{
echo $myMessage . “. <br />”;
}
echo “My message is “;
$displayMessage(“Welcome to my blog, if you have any questions just leave a comment”);
?>
</body>
</html>
Output is:
My message is Welcome to my blog, if you have any questions just leave a comment.
Here is another example where we will be having 2 parameters:
<html>
<body>
function displayMessage($myMessage, $punctuation)
{
echo $myMessage . $punctuation . “<br />”;
}
echo “My message is “;
displayMessage(“Please register here”,”.”);
?>
</body>
</html>
Output is:
My message is Please register here.
PHP Functions – Return Values
Functions can also return values.
Here is an example:
<html>
<body>
<?php
function fullName($fname, $lname)
{
$fullname = $fname . ” ” . $lname;
return $fullname;
}
echo”My full name is ” . fullName(“Bryan Joseph”,”King”);
?>
</body>
</html>
Output is:
My full name is Bryan Joseph King
No Comments Yet so far
Leave a comment
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>