Table of contents
1.
Introduction
2.
Create a Function  
2.1.
Example: Creating a Simple Function  
2.2.
Why Use Functions?  
3.
Usage of Built-in Functions
4.
Call a Function  
4.1.
Example: Calling a Function  
4.2.
Calling Functions with Arguments  
4.2.1.
Why Call Functions?  
5.
PHP Function Arguments  
5.1.
Example: Function with Arguments  
6.
Default Arguments  
6.1.
Why Use Function Arguments?  
7.
Discuss Different Filtering Options and How to Handle Different Types of Input Data
7.1.
Filtering Input Data
7.2.
Example: Validating Email Address
7.3.
Sanitizing Input Data
7.4.
Handling Numeric Input
8.
Advantages of Using PHP's Built-in Functions and Libraries
9.
Examples of Some Built-in Functions
9.1.
1. String Functions
9.2.
2. Array Functions
9.3.
3. Math Functions
9.4.
4. File Handling Functions
9.5.
5. Date and Time Functions
10.
Frequently Asked Questions
10.1.
What are Built-in Functions in PHP? 
10.2.
How do built-in functions improve security?
10.3.
Can I create my own functions in PHP?
11.
Conclusion
Last Updated: Jan 26, 2025
Medium

Built-in Functions in PHP

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

PHP, a widely-used server-side scripting language, comes with a rich set of built-in functions. These functions simplify coding tasks and make it easier to handle various operations like string manipulation, array handling, and working with databases. 

In this article, we will learn about built-in functions in PHP, their types, usage, and how they simplify coding tasks with practical examples.

Create a Function  

In PHP, a function is a block of code that performs a specific task. It allows you to reuse code, making your programs cleaner & easier to maintain. To create a function, you use the `function` keyword followed by the function name & a pair of parentheses `()`. The code inside the function is enclosed in curly braces `{}`.  

The syntax to create a function is:  

function functionName() {
    // Code to be executed
}


In this syntax:  

1. `function`: This keyword tells PHP that you’re creating a function.  
 

2. `functionName`: This is the name of the function. You can choose any name, but it should be descriptive & follow PHP naming rules (no spaces, starts with a letter or underscore).  
 

3. `()`: The parentheses are used to pass arguments (inputs) to the function. We’ll cover this later.  
 

4. `{}`: The curly braces enclose the code that will run when the function is called.  

Example: Creating a Simple Function  

Let’s create a function that prints a greeting message.  

<?php
// Define the function
function greet() {
    echo "Hello, welcome to PHP functions!";
}
// Call the function
greet();
?>


In this code:  

1. We define a function named `greet()` using the `function` keyword.  
 

2. Inside the function, we use `echo` to print a message: `"Hello, welcome to PHP functions!"`.  
 

3. After defining the function, we call it using `greet();`. When the function is called, it executes the code inside it & prints the message.  
 

Output:  

Hello, welcome to PHP functions!

Why Use Functions?  

  • Reusability: You can call the same function multiple times without rewriting the code.  
     
  • Modularity: Functions break your code into smaller, manageable parts.  
     
  • Efficiency: Built-in functions save time by providing ready-made solutions for common tasks.  

Usage of Built-in Functions

Built-in Functions in PHP are predefined and ready to use without additional libraries. They are categorized based on their purpose, such as:

  1. String Functions - Handle and manipulate string data.
     
  2. Array Functions - Perform operations on arrays.
     
  3. Math Functions - Solve mathematical problems easily.
     
  4. File Handling Functions - Manage files and directories.
     
  5. Date and Time Functions - Work with dates and timestamps.

Call a Function  

Once you’ve created a function, the next step is to call it. Calling a function means executing the code inside it. To call a function, you simply write the function name followed by parentheses `()`. If the function requires arguments (inputs), you pass them inside the parentheses.  

The syntax to call a function is:  

functionName();


In this syntax:  

1. `functionName`: This is the name of the function you want to call.  
 

2. `()`: The parentheses are used to pass arguments (if any) to the function. If the function doesn’t require arguments, you still need to include the parentheses.  

Example: Calling a Function  

Let’s use the `greet()` function we created earlier & call it multiple times to see how it works.  

<?php
// Define the function
function greet() {
    echo "Hello, welcome to PHP functions!<br>";
}
// Call the function multiple times
greet();
greet();
greet();
?>
You can also try this code with Online PHP Compiler
Run Code


In this Code:  

1. We define the `greet()` function, which prints a greeting message.  
 

2. We call the function three times using `greet();`. Each time the function is called, it executes the code inside it & prints the message.  
 

3. The `<br>` tag is added to the `echo` statement to insert a line break after each message, making the output clearer.  
 

Output:  

Hello, welcome to PHP functions!
Hello, welcome to PHP functions!
Hello, welcome to PHP functions!

Calling Functions with Arguments  

Functions become even more powerful when you pass arguments to them. Arguments are values or variables that you pass to a function to customize its behavior. We’ll cover this in detail in the next section: PHP Function Arguments.  

Why Call Functions?  

  • Execute Code: Calling a function runs the code inside it.  
     
  • Reuse Logic: You can call the same function multiple times with different inputs.  
     
  • Organize Code: Functions help you structure your code logically.  

PHP Function Arguments  

Arguments (also called parameters) are values or variables that you pass to a function to customize its behavior. They allow you to make your functions more flexible & reusable. When defining a function, you specify the arguments inside the parentheses `()`. When calling the function, you provide the values for those arguments.  

The basic syntax for a function with arguments is:  

function functionName($arg1, $arg2, ...) {
    // Code to be executed
}


In this syntax:  

1. `$arg1, $arg2, ...`: These are the arguments (inputs) that the function accepts. You can define as many arguments as needed.  
 

2. `{}`: The code inside the curly braces uses these arguments to perform tasks.  

Example: Function with Arguments  

Let’s create a function that takes two numbers as arguments & prints their sum.  

<?php
// Define the function with arguments
function addNumbers($num1, $num2) {
    $sum = $num1 + $num2;
    echo "The sum of $num1 and $num2 is: $sum<br>";
}

// Call the function with different values
addNumbers(5, 10);
addNumbers(15, 20);
addNumbers(100, 200);
?>
You can also try this code with Online PHP Compiler
Run Code


In this Code:  

1. We define a function named `addNumbers()` that takes two arguments: `$num1` & `$num2`.  
 

2. Inside the function, we calculate the sum of `$num1` & `$num2` & store it in the variable `$sum`.  
 

3. We use `echo` to print the result. 
 

4. We call the function three times with different values for `$num1` & `$num2`. Each time, the function calculates & prints the sum of the provided numbers.  


Output:  

The sum of 5 and 10 is: 15
The sum of 15 and 20 is: 35
The sum of 100 and 200 is: 300

Default Arguments  

You can also provide default values for arguments. If a value is not passed for that argument when calling the function, the default value is used.  

<?php
// Define the function with a default argument
function greetUser($name = "Guest") {
    echo "Hello, $name!<br>";
}

// Call the function with and without arguments
greetUser("Alice");
greetUser();
?>
You can also try this code with Online PHP Compiler
Run Code


In this Code:  

1. We define a function named `greetUser()` with one argument: `$name`. The default value for `$name` is set to `"Guest"`.  
 

2. When we call `greetUser("Alice");`, the function uses the provided value `"Alice"`.  
 

3. When we call `greetUser();` without any arguments, the function uses the default value `"Guest"`.  


Output:  

Hello, Alice!
Hello, Guest!

Why Use Function Arguments?  

  • Customization: Arguments allow you to pass different values to a function, making it more versatile.  
     
  • Reusability: You can use the same function for different inputs.  
     
  • Efficiency: Functions with arguments reduce the need to write repetitive code.  

    Example: Using strlen() to Calculate String Length

The strlen() function calculates the length of a string.

<?php
$text = "Hello, Coding Ninjas!";
$length = strlen($text);
echo "The length of the string is: $length";
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

The length of the string is: 21


This function is especially useful for validating input lengths, such as passwords.

Discuss Different Filtering Options and How to Handle Different Types of Input Data

Handling user input safely is crucial for security and functionality. PHP provides built-in functions for filtering and validating input data.

Filtering Input Data

The filter_var() function is versatile and allows validation of different input types. It accepts two parameters: the data to be validated and the filter type.

Example: Validating Email Address

<?php
$email = "example@codingninjas.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email address.";
} else {
    echo "Invalid email address.";
}
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

Valid email address.

Sanitizing Input Data

To remove harmful characters, use FILTER_SANITIZE_STRING or similar filters.

Example: Sanitizing a String

<?php
$input = "<script>alert('Hacked!')</script>";
$sanitized = filter_var($input, FILTER_SANITIZE_STRING);
echo "Sanitized input: $sanitized";
?>
You can also try this code with Online PHP Compiler
Run Code

Output:

Sanitized input: alert('Hacked!')


This helps prevent cross-site scripting (XSS) attacks.

Handling Numeric Input

PHP can validate integers using FILTER_VALIDATE_INT.

Example: Validating and Using Numeric Input

<?php
$age = "25";
if (filter_var($age, FILTER_VALIDATE_INT)) {
    echo "Age is valid: $age";
} else {
    echo "Invalid age input.";
}
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

Age is valid: 25

Advantages of Using PHP's Built-in Functions and Libraries

PHP’s built-in functions offer multiple benefits:

  1. Time-saving: Predefined functions reduce development time as there is no need to write complex logic from scratch.
     
  2. Reliability: PHP’s functions are well-tested and optimized for performance.
     
  3. Security: Functions like filter_var() ensure safer handling of user inputs.
     
  4. Ease of Use: Simple syntax makes these functions accessible even for beginners.
     

By leveraging these advantages, developers can create secure and efficient applications.

Examples of Some Built-in Functions

Below are examples of common built-in functions categorized by their use cases.

1. String Functions

Example: Converting a String to Lowercase

The strtolower() function converts all characters in a string to lowercase.

<?php
$text = "WELCOME TO CODING NINJAS!";
$lowercaseText = strtolower($text);
echo $lowercaseText;
?>
You can also try this code with Online PHP Compiler
Run Code


Output:

welcome to coding ninjas!

2. Array Functions

Example: Sorting an Array

The sort() function sorts an array in ascending order.

<?php
$numbers = array(4, 2, 8, 1);
sort($numbers);
print_r($numbers);
?>
You can also try this code with Online PHP Compiler
Run Code

Output:

Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 8 )

3. Math Functions

Example: Generating a Random Number

The rand() function generates a random number.

<?php
$randomNumber = rand(1, 100);
echo "Random number: $randomNumber";
?>
You can also try this code with Online PHP Compiler
Run Code


Output

Random number: 57


(Note: The output will vary as it generates a random number.)

4. File Handling Functions

Example: Reading a File

The file_get_contents() function reads the contents of a file.

<?php
$fileContent = file_get_contents("example.txt");
echo $fileContent;
?>
You can also try this code with Online PHP Compiler
Run Code

Output:

Contents of the file.

5. Date and Time Functions

Example: Getting the Current Date and Time

The date() function retrieves the current date and time.

<?php
echo date("Y-m-d H:i:s");
?>
You can also try this code with Online PHP Compiler
Run Code

Output:

2025-01-24 14:30:45


(Note: The output will vary based on the system time.)

Frequently Asked Questions

What are Built-in Functions in PHP? 

Built-in Functions in PHP are pre-defined functions that perform specific tasks like string manipulation, file handling, and input validation.

How do built-in functions improve security?

Functions like filter_var() sanitize and validate inputs, reducing the risk of attacks such as XSS or SQL injection.

Can I create my own functions in PHP?

Yes, PHP allows you to create custom functions, but built-in functions simplify common tasks and save time.

Conclusion

Built-in Functions in PHP are important functions that simplify tasks like data handling, validation, and more. We discussed string manipulation, array operations, input filtering, and additional examples to demonstrate their versatility. These functions save time, improve security, and make coding easier for beginners and professionals alike.

Live masterclass