PHP Programming

Function

A function is a reusable block of code that performs a specific task.

Using functions prevents code repetition, makes your scripts modular, and simplifies maintenance.

In programming, functions are broadly categorized into two main types based on who creates them:

  1. User-Defined Functions
  2. Built-in (System) Functions

1. User-Defined Functions

Functions that you write yourself to handle specific logic unique to your application.

The purpose of a user-defined function is modularize code, avoid repetition, and solve custom problems.

2. Built-in Functions (Internal / Standard Library)

Functions that are pre-packaged into the programming language itself. You can use them immediately without defining how they work internally.

The purpose of pre-packaged functions is to provide ready-to-use utility for common operations like string manipulation, math calculations, array handling, and file processing.

Examples of built-in functions and their usage

  1. echo: this is used to display information on the screen
  2. strtolower: this is used to change text to lower case
  3. strtoupper: this is used to change text to upper case
  4. count: this is used to count how many elements are in an array
  5. date: this is used to display date
  6. time: this is used to display the unix timestamp.
  7. sleep: this delays or pauses script execution for a specified number of seconds.

The syntax for a user-defined function is:

function name(arguments): returnType{
    //Function code to be executed comes here
    return value;//only when the function returns something
}

In modern PHP, you can indicate the data types of your arguments (the data to pass when the function is being used)

Example

function sum(float $a, float $b): float{
    return $a+$b;
}

A function could also have empty argument. This means no data is passed to the function when being used.

Example

function welcome(): void{
    echo "WELCOME TO PHP PROGRAMMING";
}

Multiple Parameters & Default Values

You can set default values for parameters. If no argument is provided when calling the function, the default value is used.

Example

function introduce($name, $role = "Guest") {
    echo "$name is logged in as a $role.
"; }

Calling a function

A function is called (used) by using the name and passing the arguments/parameters if the function takes one.

Examples

function sum(float $a, float $b): float{
    return $a+$b;
}
echo sum(20,30);
function welcome(): void{
    echo "WELCOME TO PHP PROGRAMMING";
}
echo welcome();
function introduce($name, $role = "Guest"): void {
    echo "$name is logged in as a $role.
"; } introduce("Godwin", "Admin"); // Output: Godwin is logged in as a Admin. introduce("Mary"); // Output: Mary is logged in as a Guest.