PHP Functions


PHP true power is derived from its functions.

PHP includes more than 1000 built-in functions, and you may even develop your own individual functions. These functions are used to execute a particular operation from within a script.

You can also search for these topics, functions in php, what is php functions, use of php functions, function php use, built-in function using php, how many built-in function in php, what is built-in function in php.

PHP User Defined Functions

A function is a collection of statements that may be reused throughout a program.

When a page loads, a function does not run by itself.

By calling the function, a function will be performed.

You can also seach for these topics, user defined function in php, php user defined variable, php user defined types, how to perform user defined functions.

Create a User Defined Function in PHP

The function keyword is used to create a user-defined function in a PHP program.

Syntax :-

function functionName() {
  code to be executed;
}

Note :-

  • A function name must be start with a letter or an underscore characters. There is no case sensitivity in function names.
  • The opening curly brace ( { ) denotes the start of the function code, and the closing curly brace ( } ) denotes the end of the function.
  • To invoke or call the function, just type its name followed by brackets ().

Example :- In the following example, we define a method called sayHello() and it print a message "Hello".

<?php

//  Creating Function sayHello()

function sayHello() {
  echo "Hello";
}

//  Calling the function to execute 

sayHello();

?>

Output :-

Hello

You can also search for these topics, php create a user defined function with syntax and example, how to declare user defined function in php.

PHP Function Arguments

A function may be incomplete without arguments. Because in many situation, we have to take some inputs from users or other methods to finish the task.

Inputs can be sent via arguments to functions. An argument resembles a variable.

Arguments within the parenthesis are provided by the function name. You may add as many arguments as you would like, only separate them with a comma.

Example 1 :- The following example contains a function with a only one argument ($name).

<?php
function sayWelcome($name) {
  echo "Welcome $fname.<br />";
}

sayWelcome("James");
sayWelcome("Rohan");
sayWelcome("Peter");
?>

Output :-

Welcome James.
Welcome Rohan.
Welcome Peter.

Example 2 :- The following example has a function with two arguments sum($a and $b) and make an addition of two numbers.

<?php
function sum($a, $b) {
  $c = $a + $b;
  echo "The sum is : " . $c . "<br />";
}

sum(1, 2);
sum(5, 10);
sum(20, 5);
?>

Output :-

The sum is : 3
The sum is : 15
The sum is : 25

Note:- You have to create a function only once but you can call a function as many times you want.

You can also search for these topics, function arguments in php, php function argument example, php function argument type, php function argument type, php function argument type declaration, php argument via function.

PHP Default Argument Value

Every function argument must be provided while calling the function. You cannot missing or skip an argument.

But when a function has default value argument, We can call the function with or without the arguments if you set a default value to an argument.

Example :- A default parameter is used in the following example.

<?php declare(strict_types=1); // strict requirement
function setPrice(int $price = 50) {
  echo "The price is : $minheight <br />";
}

setPrice(350);
setPrice(); // will use the default value of 50
setPrice(135);
?>

Output :-

The price is : 350
The price is : 50
The price is : 135

You can also search for these topics, default argument value using php, php default argument value property, php function default argument value, php default argument value example, php default argument value setHeight() argument.

PHP Functions - Returning values

The return statement is used to allow a function to return a value.

Example :-

<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
  $z = $x + $y;
  return $z;
}

echo "1 + 2 = " . sum(1, 2) . "<br />";
echo "5 + 6 = " . sum(5, 6);
?>

Output :-

1 + 2 = 3
5 + 6 = 11

You can also search for these topics, php return value, php return value example, declare the return value in php, example for declare the return value in php, php function return value to variable, function return value check in php.

PHP Return Type Declarations

For the return statement, PHP 7 now enables Type Declarations. When you enable the strict requirement, it will raise a "Fatal Error" if there is a type mismatch, much like it does when you enable the type declaration for function arguments.

To specify the return function type, enter colon (:) and type curly ({) bracket on declared function, just before opening.

Example 1 :- In the next example, we provide the function's return type.

<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
  return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>

Output :-

6.4

Example 2 :- You can provide a different return type than the argument types, but you must ensure that the return is of the right type :

<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
  return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>

Output :-

6

You can also search for these topics, php return type declaration, fatal error return type in php, php return type example, php return type declaration multiple, php return type declaration object.

Passing Arguments by Reference

Arguments are normally supplied by value in PHP, which implies that the function uses a copy of the value and the variable supplied into the function cannot be altered.

Changes to the argument modify the variable that was passed in when a function parameter is given by reference. The & operator is used to convert a function parameter into a reference.

Example :- To make changes to a variable, use a pass-by-reference parameter.

<?php
function add_five(&$value) {
  $value += 5;
}

$num = 2;
add_five($num);
echo $num;
?>

Output :-

7

You can also search for these topics, passing arguments by reference in php, passing arguments by reference example, passing argument by reference values, passing argument to a function by value and by reference in php.

PHP is a Loosely Typed Language

Depending on the value of the variable, PHP automatically assigns a data type to it. Because the data types are not strictly defined, you may do operations such as adding a string to an integer without producing an error.

Type declarations were added to PHP 7 to provide for more flexibility. This allows us to define the intended data type when creating a function, and the strict declaration ensures that if the data type mismatches, a "Fatal Error" will be thrown.

Example 1 :- In the next example, we attempt to submit a number as well as a string to the function without using strict :

<?php
function addNumbers(int $a, int $b) {
  return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it will return 10
?>

Output :-

10

Declare(strict types=1); must be used to indicate strict. The first line of the PHP file must contain this information.

Example 2 :- In the next example, we attempt to submit both a number and a string to the function, but this time we include the strict declaration.

<?php declare(strict_types=1); // strict requirement

function addNumbers(int $a, int $b) {
  return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not an integer, an error will be thrown
?>

Output :-

PHP Fatal error: Uncaught TypeError: Argument 2 passed to addNumbers() must be of the type integer, string given, called in /home/bWN0Ml/prog.php on line 6 and defined in /home/bWN0Ml/prog.php:3 Stack trace: #0 /home/bWN0Ml/prog.php(6): addNumbers(5, '5 days') #1 {main} thrown in /home/bWN0Ml/prog.php on line 3

The strict declaration requires that objects be utilized in the way that they were intended.

You can also search for these topics, loosely typed language using php, php loosely typed object, php loosely typed language example, php loosely typed language using strict, php loosely typed language using string.