User-Defined Functions in PHP and Returning Multiple Values

PHP

There are a lot of in-built functions in PHP. We have seen several of those already. We talked about string functions like strpos() and mathematical functions like pow(). There is a long list of these in-built functions.

But the beauty of functions do not end there. Programmers can create their own functions to perform custom tasks. If you have to perform the same calculations again and again, they reduce the number of lines in a code. You can instead call functions multiple times and negate redundancy.

Simple Function in PHP

This is a function created without any arguments or return values.

Example:

<?php
function hello(){
  echo "Hello World";
}
hello();
echo "<br />";
//Calling it one more time
hello();
?>
Output:
Hello World
Hello World

Functions with Arguments

Functions can take in arguments which it can process within the function. If a default value for those arguments is not specified in the function declaration line, then you will have to enter values to pass in the argument. If you want to pass nothing, then still you’ll have to write NULL or “”.

Example:

<?php
function hello($word){
echo "Hello ".$word;
}
hello("World");
echo "<br />";
hello ("Ashish");
?>
Output:
Hello World
Hello Ashish
Note: Although in the example we only take in one argument, the number of arguments a function can take are not limited.

Default Values of Arguments

You can also set the default values of arguments so as to use them if the argument is not provided.

Example:

<?php
function hello($greeting,$name="Ashish"){
  echo $greeting." ".$name;
}
hello("Good Morning");
echo "<br />";
hello("Hello","Michael");
?>
Output:
Good Morning Ashish
Hello Michael

Functions with Return Values

Instead of directly printing the output from a function, you can return the value from the function. Then you can assign the value to a variable or print it directly.

Example:

<?php
function hello($greeting,$name){
  $output = $greeting." ".$name;
  return $output;
}
$out = hello("Good Morning","Ashish");
echo $out;
?>
Output:
Good Morning Ashish

Dealing with Multiple Values to Return

You cannot use two variable to return multiple values from a function. But what you can do is use arrays for returning multiple values.

Example:

<?php
function math($number1,$number2){
$add=$number1+$number2;
$subtract=$number1-$number2;
$multiply=$number1*$number2;
$divide=$number1/$number2;
$mathresults=array("Add"=>$add, "Subtract"=>$subtract, "Multiply"=>$multiply, "Divide"=>$divide);
return $mathresults;
}
$result = math(4,2);
foreach($result as $key=>$value)
{
echo $key." = ".$value;
echo "<br />";
}
?>
Output:
Add = 6
Subtract = 2
Multiply = 8
Divide = 2