Tutorial How to Create a Function in PHP


Active Coder
Apr 19, 2019
This is a very brief tutorial on how to create a function in PHP.
Functions are useful so you don't repeat code throughout the script. For example, if you write code to check if a string starts with the letter "a", you don't need to put the code in 10 different places. Let's look at an example of that...

function startsWithA($string){
    if(strpos(strtolower($string), "a")) !== 0){
        return "$string does not start with a <br />"; // does not start with the letter a
    return "$string starts with a <br />";;
echo startsWithA("acute");
echo startsWithA("triangle");
echo startsWithA("angle");

This would echo out:
acute starts with a
triangle does not start with a
angle starts with a

As you can see, there was no need to repeat the same code over and over. We use the function instead.
A function is declared with the 'function' syntax, a space, and the function name - followed by ( ) - the open and close parenthesis

    function hello(){
        echo "Hello World";

This function doesn't take a variable in the parenthesis ( ), so it does the same thing every time.
We could declare this as a static function because it's always the same.

Functions don't have to echo out anything. They should usually return a value or do something.
Let's look at an example.

function timesFourPlusThree($number){
    if(!is_int($number) & & !is_float($number)){ return false; }
    return ($number * 4) + 3;

$answer = timesFourPlusThree(5);
if($answer !== false){
echo "The answer to ($number * 4) + 3 is: $answer <br />";
} else {
echo "You must supply a valid number... <br />";

In this example we are taking a number & making sure it's an integer or a float (decimal) with is_int and is_float
If you didn't know !is_int is used to know if it's NOT an integer, and !is_float will return true if it's not a float
The exclamation tells the function to analyze the opposite (!is_string() returns true if it's not a string, but is_string() without the exclamation returns true if it IS a string)

Then if it is a number/float, we multiply the number by 4 and then add 3. We return the answer.
Below the function we say that $answer = the result of our function. We can then see if it's false or an answer. If it does not === false, we know it's a valid answer so we echo it out!

As you can see, functions are so easy to create & can definitely help with repetitive code. At Wubur, our website development company, we take functions a step further by wrapping them in classes and/or namespaces depending on the system needs. This allows us to manage data & functions in a very organized fashion. I highly recommend learning about classes after functions.
Last edited: