Home > Tutorials > PHP Tutorials > How PHP Functions Work

How PHP Functions Work

A PHP function is merely a block of code that can be defined once and then reused throughout various other parts of your script/program. Typically, a function takes an argument, or a series of arguments, and performs a predefined set of operations on them – returning a value as a result. With PHP functions, code that would otherwise be repeated often can instead exist in one place and simply be called upon in other placed.

Take note that PHP already has numerous built-in functions, such as gettype() and isset(). You can declare your own PHP functions with the function statement. So, for example:

<?php
function printName($name) {
echo "Welcome" . $name;
}
?>

Now, to use this function we simply go:

printName(Bob)

Arguments provide a way to pass input to PHP functions. When we wrote the function printName previously, we passed it an argument: Bob. The argument is available within the function as the parameter $name. This parameter takes on the value of the argument that was passed to it when the function was invoked.

Let’s take a look at another example of a PHP function and passing an argument to it:

<?php
function newLine($x) {
for ($i = 0; $i < $x; ++$i) {
echo ("<BR>\n");
}
}

echo ("line1");
newLine(5);
echo ("line2");
?>

Here we are making a simple function that creates a specific amount of line breaks when used. Our function will take in a single argument ($x) and then echo out a line break as many times as requested.

Now it’s important to take note that arguments are passed by value. What this means is that the parameter variable within the function holds a copy of whatever value was passed to it. But what happens If we don’t specify a value? In this case our example will not input any line break – basically treating it like we passed it a value of 0. We can control this however by setting a default value for our $x argument.

<?php
function newLine($x = 1) {
for ($i = 0; $i < $x; ++$i) {
echo ("<BR>\n");
}
}

echo ("line1");
newLine();
echo ("line2");
?>

Now our argument will have a default value of 1 and if we simply use our function as newLine(); our function will default to display just 1 line break.

About Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Check Also

5 Must Have WordPress Optimization Plugins For A Fast Loading Website

Having a fast loading website is essential these days. First off, users are impatient. If ...