Functions in programming are small blocks of code designed to perform specific tasks. These programming functions can be categorized into two types: user-defined functions and built-in functions. In PHP, built-in functions like phpinfo()
and the mail()
function are frequently used to simplify common tasks. In object-oriented programming (OOP), we define classes, and within those classes, we create user-defined functions to encapsulate behavior and logic, further enhancing the structure and reusability of our code.
Well PHP is a versatile and powerful server-side scripting language. The key features of PHP is that it has extensive range of built-in functions. These functions helps in creating efficient, scalable, and maintainable code. PHP beginners focus on mastering syntax and control structures but they should also try to understand PHP’s built-in functions.This can be the real game-changer in creating optimized web solutions.
Functions in PHP make code cleaner and easier to understand . It saves development time by simplifying complex operations by using simple built-in functions . PHP has built-in functions for handling strings, arrays and JSON data .These functions can be used to enhance your coding workflow. In this guide, we will explore 5 essential PHP built-in functions that every developer should be familiar with. Along with practical examples and real-world applications, these functions will not only simplify your coding tasks but also elevate your programming expertise to the next level. Whether you’re a beginner or an experienced developer, this guide will provide you with the php built-in functions to write cleaner and more efficient PHP code.
Lets dive in to this guide.
PHP Built-in Functions
PHP Array Functions
- array_map() : array_map() function is a buil-in function used to manipulate arrays. It applies a callback function and manipulate array elements and return modified elements in an array. Below I have shared an example for array_map() function .
Example:
$numbers = [2, 4, 6, 8];
$dividevalues = array_map(fn($n) => $n / 2, $numbers);
Output:
[1, 2, 3, 4]
In the above example there is $numbers array and with array_map we passed a user defined function. In this user defined function elemnts are manipulated as each number is divided by 2.So now after manipulation it returns new values in array.
2. array_reduce() : The array_reduce() function in PHP is used to reduce an array to a single value.This is done using a callback function.array_reduce() function takes a callback abd argument .Then it processes each value in the array and carries over the result to the next iteration.This ultimately produces a single value as the result.
Example of array_reduce() :
$array_of_numbers = [1, 2, 3, 4, 5];
$result_of_summation = array_reduce($array_of_numbers, function($carry, $item) {
return $carry + $item;
}, 0);
echo $result_of_summation ;
// Output: 15
In the above example sum of array numbers is displayed .Here $carry (short for “carry over”) returns the total result from the iterations of callback function.It takes the $initial parameter or null if no initial value is provided.$item is the current processed value of the array element in the iteration.
Each element of the array is passed as $item to the callback one at a time.
PHP Built-in Sanitization ,Formatting and String Functions
1.filter_var() : filter_var() function validates and sanitizes user input . In the below example,it validates email field data.
$email = "phpguruacademy@example.com";
$isValid = filter_var($email, FILTER_VALIDATE_EMAIL);
Output:
true if valid email
In the above example filter_var() function validates emailid address.
3.strpos() : Finds the position of first occurence of a part of a string inside a main string.
$mainstring = "Hello, everyone!";
$position = strpos($mainstring, 'everyone');
Ouput:
7
In the above example there is a string variable named as $mainstring.Now if we want to know the position of “everyone” which is a substring inside the $mainstring variable so we can use strpos() function for that.It returns the position as 7 .
4. empty() : This function checks whether the variable has any value or not.
$text="hello";
if(!empty($text)){
echo "Value is present":
}
else{
echo "Value is not present":
}
Output:
"Value is present":
In the above example with if clause we check that the variable is empty or not . If the variable has no value it returns the value inside the if condition otherwise it returns the value in else clause.Here $text has value so the value returned is “Value is present” .
5. trim() :This function removes whitespace from beginning and end of string.
$inputData = " Hello everyone! ";
$cleanInput = trim($inputData);
Output:
"Hello everyone!"
In the above example trim() function removes whitespace from both sides of string variable.
PHP Troubleshooting and Mail Handling Built-in Functions
6 .mail() : mail() function is used to send email messages directly from php script .It’s a simple and fast way to send message .We donot need to set email server for sending mails .
Example of mail() function :
mail(to, subject, message, headers, parameters);
Explanation below for mail() function example:
to: The recipient’s email address (string).
subject: The subject of the email (string).
message: The body of the email (string).
headers (optional): Additional headers, such as From, Reply-To, Cc, Bcc, and Content-Type (string).
parameters (optional): Additional parameters for the sendmail program (used only on Unix-based systems).
6.phpinfo() : phpinfo() function is used to provide detailed information about the PHP environment on a server. This displays configuration settings and environmental details about the server.So this can be used for deugging and troubleshooting
Example of phpinfo() function :
<?php
phpinfo();
?>
User Defined Functions
Functions which are defined by developer during coding phase are the user defined functions. These are small functions which are used because of the following:
1.Perform Specific Tasks
1.Reusability Of Code
2.Organizing Code
Perform Specific Tasks
User defined functions are defined to perform specific tasks. Suppose you want to create an application which is an ecommerce application .In this ecommerce application you want to create a report tool .This tool will generate analytics report for your application.So you need to create a tool to generate user details with orders placed. So you need to create custom function for this. So you will define userdefined functions to generate user order details . So lets see how we will create a userdefined function for this .
We will define a function with name as UserReorts with brackets enclosed .Inside that function we will write code to fetch user details with order placed by them. Then the code for generate reports will be written. Check the code below :
function userReports() {
/*Code for fetching data of user orders and user details and generating reports*/
}
Now how we are going to use this function in our code.Lets see below example to understand this.
Letssee we have code where we want to fetch this report.So we will simply call this function by it’s name and add small brackets or parentheses after the function name.heck the code below
UserReports();
//Output
Display all user order details
Reusablity Of Code
By using user defined we can reuse the code for similar type of tasks .Suppose we are creating another function from which sends email to users after each order placed .So here we can use the same function. We donot have to create a new function for this.This saves our time and resource. This provides the code reusability in an application.
Organizing Code
Userdefined functions provide a way to split your code functionality into parts. This organizes code in a modular way and thus guides a developer to understand the code more clearly. Suppose if code is divided into modules and each module is divided in to smaller chunks of code .Each chunk of code has it’s own userdefined functions .So these functions can be simply used by calling it, making learning and using code easy.
So in this guide we explored some important php in-built functions .These functions make complex code to simpler solutions . These functions are useful for PHP beginners as well as PHP experts. We also learned how to define and use userdefined functions.