PHP - Functions
PHP is a server-side scripting language and has a large number of built-in functions that allow developers to perform various operations such as string manipulation, arithmetic calculations, array manipulation, and more.
PHP Built-in Functions
A function is a self-contained block of code that performs a specific task.
PHP has a huge collection of internal or built-in functions that you can call directly within your PHP scripts to perform a specific task, like gettype(), print_r(), var_dump, etc.
Please check out PHP reference section for a complete list of useful PHP built-in functions.
PHP User-Defined Functions
In addition to the built-in functions, PHP also allows you to define your own functions. It is a way to create reusable code packages that perform specific tasks and can be kept and maintained separately form main program. Here are some advantages of using functions:
- Functions reduces the repetition of code within a program — Function allows you to extract commonly used block of code into a single component. Now you can perform the same task by calling this function wherever you want within your script without having to copy and paste the same block of code again and again.
- Functions makes the code much easier to maintain — Since a function created once can be used many times, so any changes made inside a function automatically implemented at all the places without touching the several files.
- Functions makes it easier to eliminate the errors — When the program is subdivided into functions, if any error occur you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier.
- Functions can be reused in other application — Because a function is separated from the rest of the script, it's easy to reuse the same function in other applications just by including the php file containing those functions.
The following section will show you how easily you can define your own function in PHP.
Creating and Invoking Functions
The basic syntax of creating a custom function can be give with:
function functionName(){
// Code to be executed
}
This is a simple example of an user-defined function, that display today's date:
<?php
// Defining function
function whatIsToday(){
echo "Today is " . date('l', mktime());
}
// Calling function
whatIsToday();
?>