Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
What is PHP Function?
2.
User-Defined Functions in PHP
3.
Importance of using PHP Functions
4.
PHP: Loosely Typed Programming Language
5.
Function Argument in PHP
6.
Default Argument in PHP
7.
Call by Reference in PHP
8.
Return Value in PHP
9.
Frequently Asked Questions
10.
Key Takeaways
Last Updated: Mar 27, 2024

Functions in PHP

Author Sneha Mallik
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

PHP (also known as Hypertext Preprocessor) is a general-purpose programming language that may be used to create interactive and dynamic websites. It was one of the first server side languages to be integrated into HTML, making it easy to add functionality to the webpages without accessing data from separate files.

What is PHP Function?

A PHP function is a section of code that can be used repeatedly. It accepts argument lists as input and returns a value. PHP comes with thousands of in-built functions which provide different functionalities.

Conditional functions(e.g., if, if-else, nested if-else, etc. ), Function within Functions, and Recursive functions are various functions that can be defined in PHP.

User-Defined Functions in PHP

User-defined functions can be created by ourselves in addition to the in-built PHP functions.

  • A function is a group or block of statements used repeatedly in a code or program.
  • When a page loads, the function won't run automatically.
  • The call to a function will cause it to be executed.

Example:

We'll make a function called "printMessage()" in the example below. The beginning of the function code is indicated by the opening curly brace '{', and the end of the function is indicated by the closing curly brace '}'. The result of the function is "Hello! Welcome to CodingNinjas". Simply write the function's name in brackets () to invoke it:

<?php
function printMessage() {
  echo "Hello! Welcome to CodingNinjas";
}
// function call
printMessage();
?>

Output

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Importance of using PHP Functions

  • Reusability of code: Unlike other programming languages, PHP functions are defined only once and can be called several times.
  • Less Coding: It saves a lot of code because the reasoning or logic doesn't have to be written many times. You can write the logic only once and reuse it by using functions.
  • Simple to understand: The programming logic is separated using PHP functions. Because every logic is divided into functions, it is easier to understand the application's flow.

PHP: Loosely Typed Programming Language

Depending on the variable's value, PHP assigns it a data type automatically. We can perform functions like adding a string to an integer without raising an error because the data types aren't defined in a strict sense.

Type declarations were introduced in PHP 7. This will allow us to define the intended data type when creating a function, and strict declaration ensures that if the data type is mismatched, a 'Fatal Error' is generated.

Without using strict, we try to pass both a number and a string to the function in the following example:

<?php
function subtractionOfNumbers(int $x, int $y) {
  return $x - $y;
}
echo subtractionOfNumbers(10, "4 weeks"); 
// here strict is NOT enabled,therefore "4 weeks" is changed to int(4), and it will return 6
?>

Output:

6

 

'declare(strict types=1)' is required to enable the strict declaration. The first line of the PHP file must contain this.

We try to submit both number and string to the function in the following example, but in this, we've included the strict declaration:

<?php declare(strict_types=1); // the strict declaration
function subtractionOfNumbers(int $x, int $y) {
  return $x - $y;
}
echo subtractionOfNumbers(10, "4 weeks"); 
// here strict is enabled, as "4 weeks" is not an integer, it will throw a 'FATAL ERROR'
?>

 

Output:

Function Argument in PHP

The information can be passed to the PHP function via arguments/parameters separated by a comma.

Call by Reference, Call by Value (default), Default argument values, and Variable-length argument list are all supported by PHP.

Let us look at an example of passing a single argument to a PHP function.

<?php  
function welcomeUsers($user){  
echo "Welcome $user!<br/><br/>";  
}  
welcomeUsers("Sam");  
welcomeUsers("Ankit");  
welcomeUsers("John");  
?>  

Output

Let us look at an example of passing three arguments to a PHP function.

<?php  
function welcomeUsers($user,$batch,$rollno){  
echo "Welcome $user! You are from batch $batch and your roll no. is $rollno. <br/><br/>";  
}  
welcomeUsers("Sam",1,001);  
welcomeUsers("Ankit",1,002);  
welcomeUsers("John",2,003);  
welcomeUsers("Harry",3,004);  
?> 

Output

Default Argument in PHP

In function, we can set a default argument value. If we don't give an argument when calling a PHP function, it will use the default value. Let us look at a simple example of a PHP function that uses the default parameter value.

<?php  
function welcomeUsers($user="Harry"){  
echo "Welcome $user!<br/><br/>";  
}  
welcomeUsers("Sam");  
welcomeUsers("Ankit");  
welcomeUsers(); // We will check the default argument by passing no value here
?>  

Output

Call by Reference in PHP

By default, the value provided to the function does not affect the default value (i.e., call by value). However, we can accomplish this by passing the value as a reference.

The value given to the function is called by default. We must use the ampersand, i.e., the '&' symbol before the parameter name to pass the value as a reference.

Now let us look at a simple call-by-reference example in PHP.

<?php
function addString(&$string2) {
  $string2 .= 'Happy New year!';
}
$string1 = 'Coding Ninjas wishes you a ';
addString($string1);
echo $string1; 
?>

Output

Return Value in PHP

Let us look at a simple example of a PHP function that returns a value.

<?php  
function mathFunc($x){  
return $x*$x+$x/$x;  
}  
echo "The math function will have the result : ".mathFunc(5);  
?>  

Output

Frequently Asked Questions

 

1. What do you mean by return type declarations in PHP?

Ans: The return statement in PHP 7 supports Type Declarations. Enabling the strict requirement, like with the type declaration for function parameters, will result in a "Fatal Error" if a type mismatch occurs.

Add a colon ':' and the return type right before the opening curly '{' bracket when declaring the function to define a type for the function return.

 

2. Are function names in PHP case-sensitive?

Ans: No, the function names in PHP are not case-sensitive. The name of a function must begin with a letter or an underscore.

Key Takeaways

In this blog, we have learned the concepts of PHP functions and how they are used, their advantages, the user-defined functions in PHP, and many more.

Go through PHP archives to look through more PHP blogs and deeply understand the concept of PHP. Prepare for the PHP interview rounds by going through the PHP Interview questions: Part 1 | Coding Ninjas Blog.

Credits: GIPHY

Happy Developing!

Live masterclass