PHP Lesson 21: How to create Fuctions Example

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

PHP Lesson 21: How to create Fuctions Example - PHP Lesson 21: How to create Fuctions Example - PHP Lesson 21: How to create Fuctions Example - php functions
php functions

So far, we have mainly used functions that provide PHP. This tutorial is about writing and using your own functions.

Often you have a certain programming problem that occurs in several places, for example, you want to calculate values of a certain mathematical function in several places of your scripts. Here every time to copy the code would greatly inflate the scripts and make the program code also difficult to maintain. If you have to change something on the code, for example, you would have to pick out all the digits and make the change. Therefore, it is recommended to encapsulate certain functionalities and define them as a separate function.

Defining your own functions – PHP

Below is a small example. Suppose we have two numbers $a and $b and if $a + $b is greater than  $a * $b , let’s say  $a + $b. This can look like a function like this:

function calculate ($a, $b) {
   $addition = $a + $b;
   $multiplication = $a * $b;
   if ($addition> $multiplication) {
      return $addition;
   } else {
      return $multiplication;
echo calculate(1,10). "<br />";
echo calculate(2,3). "<br />";
echo calculate(-5,8). "<br />";

A separate function starts with the keyword function followed by the function name, in this case, add up. This is followed by the various parameters of the function, separated by commas. Here we have decided on the two parameters $a and $b. We can specify more parameters or none at all, depending on the task and problem we want to solve.

This is followed by the trunk of the function. There we first calculate the result of the addition, then the result of the multiplication of the two parameters. If the result of the addition is greater than that of the multiplication, we use the keyword return to return a value. With return, a value or a variable is returned and the function will not be executed.

We can call our function quite normally like any other function in PHP. We pass certain values or variables containing the values and get the result back.

Parameter of a function

As shown in the previous example, a function can have any number of parameters. We can then access the values of the parameters in the function body as any other variable. The variables are valid only within one function, ie changing their variables within one function body does not affect other variables (except global variables such as $_SESSION).

Here is a short example:

$name = "Robort";
echo "Hello, my name is $name";

function myfunction($newname) {
   if (strlen($new_name) <3) {
      echo "New name too short";
   } else {
     $name = $new_name;
     echo "In the function you are called $name";

echo "The value of the variable name is: $name";

Having the variable only the validity within the hull has a good reason. So you prevent a function from modifying any values in your script without you wanting to. On the other hand, this also means that you have to pass all variables as parameters that you want to use in the function.

The following example does not work :

weekday = "Sunday";
function greeting($name) {
   echo "Hello $name, I wish you a nice weekday";


The correct variant here is:

$weekday = "Sunday";

function greeting($name, $tag_in_of_week) {
   echo "Hello $name, I wish you a nice $tag_in_the_week";

greeting("John", $weekday);

In the latter example, we decided to name the parameter $tag_in_of_week. You could have called it weekday or any other valid name, that would not matter. Within the function body, we can only use variables that we have either defined as parameters of the function ($name, $tag_in_of_week) or that we have defined in the function body

Optional parameters for functions

Often you do not want to pass a value for all the parameters of a function, but a certain default value should be assumed. We can easily do this in PHP by writing the default value after an equals sign after the parameter:

function linebreak_resetting($text, $new_character = "<br />") {
   return str_replace("\n", $new_char, $text);

$text = "This \n is an \n example \n\n";
echo linebreak_resetting($text);
echo linebreak_resetting($text, "--BREAK--");

The function in the above example has two parameters, once the parameter $text which must always be set. And the parameter $new_character. If no value was specified for this, the value <br /> is assumed.

Now we can call the function with a parameter and pass only $ text, or we use both parameters. You can set default values for all parameters of a function, but this does not work, first set a mandatory parameter, then an optional parameter and then another mandatory parameter. This means that you first have to define all mandatory parameters and then you can define the optional parameters.

If you call a function with default values for parameters, you must also pay attention to the order of the parameters. For example, it is not possible to use the default value for the first parameter but to set it for the second one. See the following example:

function my_function($parameter1 = "one", $parameter2 = "two", $parameter3 = "three") {
  echo "Parameter1: $parameter1 <br />";
  echo "Parameter2: $parameter2 <br />";
  echo "Parameter2: $parameter3 <br />";

echo my_function();
echo my_function("Value1");
echo my_function("Value1", "Value2");
echo my_function("Value1", "Value2", "Value3");

Suppose you want to call the above function and set only a value for $parameter3. Unfortunately, this is not possible, you must first set values for $parameter1 and $parameter2. Therefore, it makes sense to have a certain order in the parameters, ie to define the parameters that are most often used first and those that are least frequently used as the last one.

Return values of functions

Functions can be returned values using the return command. The use of the command is optional, that is, a function can return a value, but does not have to. In our initial example, we have the function compute() we have already seen the use of return. It is important to remember that the function will not continue to run as soon as we execute return. The following example illustrates this:

function compute($a, $b) {
   if ($a == 0 or $b == 0) {
      return zero;
   echo "Calculate result for $a and $b :";
   return 10.0/$a + 100.0/$b;
echo compute(10,2);
echo compute(0,10);
echo compute(5,2);

If one of the parameters has the value 0, a null is returned. Otherwise, an echo will generate an output and a value will be calculated and returned.

Return multiple variables
With return, we can return a value. But sometimes we want to return more values, for example, we want to find and replace a certain word in a text, and we also want to know how often it has been replaced. To achieve this, one typically returns the various variables in an array. The following example illustrates this:

function find_and_replace($text, $search, $replace) {
   $number = substr_count($text, $search);
   $new_text = str_replace($search, $replace, $text);
   return array($number, $new_text);

$text = "This is an example and it's a pretty simple example";
$result = find_and_replace($text, "is", "was");

echo "Count:".$result[0]. "<br />";
echo "New text:".$result[1];

First, we determine by substr_count ($text, $search) How often $search occurs in $text. Then we use str_replace ($search, $replace, $text) to replace all occurrences. Both results, ie the number of occurrences and the new text, are returned as an array. We can then access the individual results via the indexes[0] for the number and [1] for the frequency.

If we want to return many values, then the numbering of the results can quickly become confusing. It is then advisable to resort to associative arrays:

function find_and_replace($text, $search, $replace) {
   $number = substr_count($text, $search);
   $new_text = str_replace ($search, $replace, $text);
   return array("number" => $number, "new_text" => $new_text);

$text = "This is an example and it's a pretty simple example";
$result = find_and_replace($text, "is", "was");

echo "Count:".$result['number']."<br />";
echo "New text:".$result['new_text'];

Tips for a clean programming style

To conclude the tutorial a few tips for a clean programming style regarding functions:

  • One task per function – your functions should not try to solve all tasks at once. Instead, it makes sense to solve only one task per function. If you can subdivide complex tasks into smaller tasks, then it makes sense to write your own functions. For example, if you want to check the input in a form and then save the data, then you should do it in several ways. For example, a function to check individual fields, for example, the e-mail field, then a function that checks all fields correctly completed and finally a function to save the form.
  • Choosing meaningful function names – Function names like a()b() may be short, but they will say little later if you call the function in your script. Instead, select meaningful function names so that the name already indicates what the function does. If a meaningful name becomes too long, is this perhaps an indication that your function is too complex and you’d rather break it down into different functions?
  • No echo output in functions – Here in the tutorial we have occasionally echoed text output in the functions. However, this is bad style, because later when you call the function you can not influence anymore if you want the output or not. Instead, you should rather work with returns. So instead of echoing a text, return it by return and you’re free to decide later if you want to output the text or if you want to process it further.
  • Documentation of the function – It is advisable to briefly comment on the function. Write a comment before the function. Often one briefly documents the functionality, the parameters and the return value. Write this documentation before you write the function, this helps you to have a clearer style. A good and widely used documentation can look like this:
/ **
 * Checks if the user is of legal age. If so, true is returned
 * @param string birthdate Date of birth of the user
 * @param int adulthood From how many years one is of age, by default 18 years
 * @return boolean true if the user is of age, otherwise false
 * /
function isAdult($birthdate, $adulthood = 18) {
   // Here is my code

First, the basic function is described in the comment. Followed by the parameters we introduce with the word @param, followed by the type (eg string or int) and a short description. Finally, the return value we initiate with @return, followed by the type of the return value and again a brief description.

This is just an example of how you can comment on functions, the documentation is not mandatory. But it helps you if you look at the code later.

About The Author

Related posts

Leave a Reply