PHP Functions: Built-in, String & Numeric Examples

⚡ Smart Summary

Functions in PHP are reusable blocks of code that perform a specific task, take parameters, and optionally return a value. This walkthrough explains why functions matter, surveys the built-in string, numeric, and date functions, and shows how to write user-defined functions with parameters and return values.

  • 🧩 What Functions Do: A function groups related code into a named, reusable block that takes input parameters and may return a result.
  • ♻️ Why Use Them: Functions improve code organization, allow reuse across scripts, and centralize maintenance so fixes happen in one place.
  • 📦 Built-in Library: PHP ships with hundreds of built-in functions covering strings, numbers, dates, arrays, files, and databases.
  • 🔢 Numeric Helpers: Functions like number_format, round, sqrt, and rand format and compute numeric values quickly.
  • 🛠️ User-Defined: You declare custom functions with the function keyword, following naming rules, to handle routine tasks like validation.
  • 📥 Parameters and Return: Parameters can have default values or be passed by reference, and return sends a value back to the caller.
  • 🤖 AI Assist: AI tools can write a function from a description and refactor repeated code into clean reusable functions.

PHP Functions

What is a Function in PHP?

A function in PHP is a reusable piece or block of code that performs a specific action. It takes input from the user in the form of parameters, performs certain actions, and gives the output. Functions can either return values when called or simply perform an operation without returning any value.

PHP has over 700 built-in functions that perform different tasks.

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 the time of reinventing the wheel when we want to perform 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 are predefined functions in PHP that exist in the installation package.

These PHP inbuilt functions are what make PHP a very efficient and productive scripting language.

The built-in functions of PHP can be classified into many categories. Below is a list of the main categories.

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 functions can be used to format numbers, return constants, perform mathematical computations, and more.

The table below shows the common PHP numeric functions.

Function Description Example Output
is_numeric Accepts an argument and returns true if it is numeric and false if it is not
<?php
if(is_numeric("guru"))
{
echo "true";
}
else
{
echo "false";
}
?>
false
<?php
if(is_numeric(123))
{
echo "true";
}
else
{
echo "false";
}
?>
true
number_format Used to format a numeric value using digit separators and decimal points
<?php
echo number_format(2509663);
?>
2,509,663
rand Used to generate a random number.
<?php
echo rand();
?>
Random number
round Rounds off a number with decimal points to the nearest whole number.
<?php
echo round(3.49);
?>
3
sqrt Returns the square root of a number
<?php
echo sqrt(100);
?>
10
cos Returns the cosine
<?php
echo cos(45);
?>
0.52532198881773
sin Returns the sine
<?php
echo sin(45);
?>
0.85090352453412
tan Returns the tangent
<?php
echo tan(45);
?>
1.6197751905439
pi Constant that returns the value of PI
<?php
echo pi();
?>
3.1415926535898

Date Function

The date function is used to format a Unix date and time to a human readable format.

Check the article on PHP date functions for more details.

Other functions include:

Why use User Defined Functions?

User defined functions come in handy when:

  • you have routine tasks in your application such as adding data to the database
  • performing validation checks on the data
  • authenticating users in the system, and similar tasks.

These activities will be spread across a number of pages. Creating a function that all these pages can call is one of the features that make PHP a powerful scripting language.

Before we create our first user defined function, let us look at the rules that we must follow when creating our own 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 good practice to use descriptive function names.
  • Functions can optionally accept parameters and return values too.

Let us now create our first function. We will create a very basic function that illustrates the major components of a function in PHP.

<?php

// define a function that adds two numbers

function add_numbers(){
echo 1 + 2;
}
add_numbers ();
?>

Output:

3

HERE,

  • “function…(){…}” is the function block that tells PHP that you are defining a custom function
  • “add_numbers” is the function name that will be called when using the function.
  • “()” can be used to pass parameters to the function.
  • “echo 1 + 2;” is the function block of code that is executed. It could be any code other than the one used in the above example.

Let us now look at a fairly complex example that accepts a parameter and displays a message, just like the above function.

Suppose we want to write a function that prints the user name on the screen. We can write a custom function that accepts the user name and displays it on the screen.

The code below shows the implementation.

<?php
function display_name($name)
{
echo "Hello " . $name;
}
display_name("Martin Luther King");
?>

Output:

Hello Martin Luther King

HERE,

  • “($name)” is the function parameter called name. The value passed to the function when it is called is displayed after the word Hello.

Let us now look at a function that accepts a parameter and then returns a value. We will create a function that converts kilometers to miles. The kilometers will be passed as a parameter, and the function will return the miles equivalent. The code below shows the implementation.

<?php
function kilometers_to_miles($kilometers = 0)
{
$miles_scale = 0.62;
return $kilometers * $miles_scale;
}
echo kilometers_to_miles(100);
?>

Output:

62

PHP Function Parameters and Return Values

Parameters let a function work on different input each time it runs, and the return statement sends a result back to the caller. PHP offers several ways to control how parameters behave.

  • Default values: as in kilometers_to_miles($kilometers = 0), a default is used when the caller omits that argument.
  • Pass by reference: prefixing a parameter with & lets the function change the caller’s original variable instead of a copy.
  • Return values: return ends the function and hands a value back; without it, the function returns null.

The example below uses a reference parameter and a default rate to add tax to a price in place.

<?php
function addTax(&$price, $rate = 0.1)
{
$price += $price * $rate;
}
$total = 100;
addTax($total);
echo $total;
?>

Output:

110

Because $price is passed by reference, the function updates the original $total variable directly, so the echoed value is 110.

FAQs

PHP functions return one value, so return an array to send back several results, for example return [$min, $max];. The caller can unpack them with list() or the short syntax [$a, $b] = getRange();.

An anonymous function is a function with no name, stored in a variable or passed as an argument. Closures can capture outer variables with the use keyword, which is handy for callbacks like array_map and usort.

Introduced in PHP 7.4, an arrow function uses the syntax fn($x) => $x * 2. It is a shorter closure that automatically captures outer variables by value, ideal for concise one-line callbacks.

Yes. Describe the input, the task, and the expected output, and AI can generate the function with parameters, a return value, and basic validation. Review edge cases and test before using it.

Yes. Paste the duplicated code, and AI can extract it into a single parameterized function and update the call sites. Check that the extracted parameters cover every difference between the original copies.

Summarize this post with: