PHP Tutorial
User defined functions

What is a function and how we create one?

A function is a group of statements that can be called multiple times across our script. By using functions we can avoid repetitive code by writing once our statements (the code) inside the function and using it multiple times when we need it.

User-defined functions help us to make our code cleaner, easier to write and easier to change it (once you update the function, it will also be updated everywhere it's used).


//here is where we define/create the function
function getGreetings()
   //here is the function's body
   echo 'Welcome to Have fun!';

//and here we call/execute the function
//this will execute the statements inside the function's body
//will output "Welcome to Have fun!"

//and we can call again and again the function
//will return same output as before

As we can see from the example above, we must first use the keyword function before writing the name of the function.

The name of the function follows the same rules as when setting the names of the variables (start the name with letter or underscore, after that you can use only letters, numbers and underscore). One exception is that the name is case-insensitive (PHP will see the uppercase and the lowercase letters from the name in the same way, so you could call later the "getGreetings()" function either by "getGreetings()" or "getgreetings()" and PHP will make no difference, but we should avoid confusion by calling them as we defined them initially).