
A PHP function provides code that a PHP script can call to perform a task, such as Count, file get contents and header . The PHP language supports both procedural and object-oriented programming paradigms. In the procedural space, functions are a key building-block for developing and maintaining streamlined applications.
Why use Functions?
- Better code organization – PHP functions allow us to group blocks of related code that perform a specific task together.
- Reusability – once defined, a function can be called by a number of scripts in our PHP files. This saves us time of reinventing the wheel when we want to perform some routine tasks such as connecting to the database
- Easy maintenance- updates to the system only need to be made in one place.
PHP Built in Functions
Built-in functions in PHP are pre-defined functions that are available for use without the need for explicit declaration or definition. These functions provide a wide range of functionality, from basic operations like string manipulation and mathematical calculations to more advanced tasks such as database connectivity and file handling.
String Functions
These are functions that manipulate string data, refer to the article on strings for implementation examples of string functions
Numeric Functions
Numeric functions in PHP are the functions that return numeric results.
Numeric php function can be used to format numbers, return constants, perform mathematical computations etc.
Date Function
The date function is used to format Unix date and time to human readable format.
Check the article on PHP date functions for more details.
Other functions
These include;
Arrays – see the article on arrays for examples
Files – see the article on files for examples
Database functions – see the article on MySQL PHP and other database access methods v2
Why use User Defined Functions?
- Function names must start with a letter or an underscore but not a number
- The function name must be unique
- The function name must not contain spaces
- It is considered a good practice to use descriptive function names.
- Functions can optionally accept parameters and return values too.
Example :-
<?php
function kilometers_to_miles($kilometers = 0)
{
$miles_scale = 0.62;
return $kilometers * $miles_scale;
}
echo kilometers_to_miles(100);
?>
Output
62