PHP Basics: Functions

Functions in PHP

PHP allows you to write functions similarly to the way functions are written in other languages. Functions in PHP provide the same advantages that they provide in other languages also. Functions provide a way to encapsulate a block of code so it can be reused as often as needed. This allows you to avoid rewriting the same blocks of code over again. Which makes your job easier by writing less code. This also keeps your from having to write similar or the same block of code more than once.

The basic syntax is very similar to what you may already be familiar with.

function  function_name() {
... code ...
}

Function names must be unique. The same name may not appear in different documents.

Use a function by defining it then call it by name. For example:

<?php
function hello_Wrold() {
echo  "<p>Hello World</p>";
}

hello_world();
?>

The code block above defines a function, named hello, and then calls the function on the line below. Each time this function is called PHP should print a paragraph containing the words Hello World. The code block below would print three paragraphs.

<?php
function hello_world() {
echo  "<p>Hello World</p>";
}

hello_world();
hello_world();
hello_world();
?>

This might not seem very exciting at this point. Where functions become very useful is when they are set up to accept parameters. Parameters are variables that hold values passed along to a function. These values can be used to tell a function how to do what it does.

For example, the following modifies the original hello function so that we can tell it how many paragraphs to print.

<?php
function hello_world( $n ) {
while( $n > 0 )  {
echo "<p>Hello World</p>";
$n --;
}
}

hello_world( 3 );
?>

The example above calls the hello function and includes the parameter 3: hello(3). This causes the function to print the paragraph 3 times.

If you have a default value for a parameter that you use often you can assign that to a parameter like this:

<?php
function hello_world( $n = 1 ) {
while( $n > 0 )  {
echo "<p>Hello World</p>";
$n --;
}
}

hello_world();
?>

If no parameter is included the function uses the default value. For example, the following would print one paragraph: hello(), this would print 5 paragraphs: hello(5).

Functions can also return a value. The following rearranges the code above to have the function return paragraphs.

<?php
function hello_world( $n = 1 ) {
$str = "";
while( $n > 0 )  {
$str .= "<p>Hello World</p>";
$n --;
}
return( $str );
}

echo hello_world();
?>

Here the function creates a string which is returned and echoed at the point where the function was called.

Where to place functions
It’s best to define all of your functions in the same place. A good strategy is to place them all in a PHP file and use include or require to make the code available on any page that might use it.

Leave a Reply

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