Functions in PHP

A function will let you create a logic grouping of code to perform one or more related or different tasks. This helps a programmer in many ways. Using functions, you may avoid writing repetitive code in your programs, change the logic at one place and it reflects at every place where the function is used. Let us begin by taking a look at this example:

Our requirement is to print numbers from 1 to 10 and it is how basic coding would look like:

<?php
echo "1";
echo 
"2";
echo 
"3";
echo 
"4";
echo 
"5";
echo 
"6";
echo 
"7";
echo 
"8";
echo 
"9";
echo 
"10";
?> 

Yes, it was easy to write 10 lines of 'echo' and obtain the output. But what if you were asked to write code to print 1 to 1000 or even more? I see that you are now thinking about steps to accomplish this task. Don't worry, this is what functions are used for! When you write a function, it will become easy to just pass the starting and ending number and the list will be automatically printed.
A simple function to print all numbers between two numbers may look like this:

<?php
function print_numbers($start_num$end_num) {
      for (
$i=$start_num,$i<=$end_num,$i++) {
      echo 
$i;
      
$i++;
      }
}
?>

Now, if you were to call this function to print values between 10 and 100, all you will have to do is this:

print_numbers(10, 100) // This will print numbers between 10 and 100

The values which are being passed to function (in our example $start_num and $end_num) are called parameters or arguments. You may specify many number of parameters based on your requirements. The same function can be used to print a range of numbers such as:

print_numbers(10, 100)
print_numbers(25, 100)
print_numbers(20, 40)

Going forward, if you want to print a list of numbers between two numbers, all you have to do is call the function and pass the starting and ending numbers (as parameters/arguments). The code inside the function will do the rest.

Let us now look at declaring a function in PHP and learn more about it.