Open In App

How the User-Defined Function differs from Built-in Function in PHP ?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In PHP, functions are blocks of reusable code that perform specific tasks. They enhance code readability, modularity, and maintainability by encapsulating logic into named units. PHP functions can be categorized into two main types: user-defined functions and built-in functions.

User-Defined Functions

User-defined functions are functions created by developers to perform custom tasks specific to their application’s requirements. These functions are defined using the function keyword followed by a function name, parameters (optional), and a block of code encapsulated within curly braces.

Syntax:

function functionName($param1, $param2, ...) {
// Function body
// Perform specific tasks here
return $result; // Optional
}

Example: Illustration of User-defined Function

PHP




<?php
// User-defined function to calculate the square of a number
function square($num)
{
    return $num * $num;
}
 
// Calling the function
$result = square(5); // Output: 25
print_r($result);
 
?>


Output

25




Built-In Functions

Built-in functions, also known as native functions, are predefined functions provided by the PHP language itself. Built-in functions cover a wide range of functionalities, including string manipulation, array operations, file handling, mathematical calculations, and more.

Example: Illustration of Built-In Function

PHP




<?php
// Using built-in functions
$string = "Hello, World!";
$length = strlen($string); // Get the length of the string
$uppercase = strtoupper($string); // Convert the string to uppercase
$substring = substr($string, 0, 5); // Get a substring from the string
 
print_r($length);
echo " ";
print_r($uppercase);
echo " ";
print_r($substring);
 
?>


Output

13 HELLO, WORLD! Hello




Difference between User-Defined and Built-In Functions

User-Defined Functions Built-In Functions
Created by developers to perform custom tasks Predefined functions provided by the PHP language
Defined using the function keyword followed by a name and code block Available for use without the need for explicit definition
Can accept parameters and return values Cover a wide range of functionalities including string manipulation, array operations, file handling, etc.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads