PHP Functions

PHP Functions

Posted by

In this article, we will cover the following topics:

Introduction of PHP Functions

PHP functions are a piece of code that can be reused.

Advantages of PHP functions:

  • Code Reusability.
  • Reducing code duplication.
  • Break a larger number of codes into small pieces.

PHP functions are divided into two sections such as Built-in function and user-defined function. Built-in functions are part of the language of PHP. User-Defined function, that can be created by a programmer according to needs. The user-Defined function executes by the call of the function.

Declaring Functions:

A PHP function declares by keyword function.

Syntax:

In the above syntax,

  1. Start a keyword function for creating a function.
  2. Put the name of function example: userDefineFunctionName.
  3. Start a curly( { ) brace.
  4. Write a block of code.
  5. Close curly( } ) brace.

Example:

In the above example, define a function “add” and it is adding two values (10 + 7). After declaration, it will show 17 as an output. If you do not declare the function then it will not show anything.

Passing Arguments to Functions:

PHP function allows passing arguments to the function. You can pass multiple arguments according to requirements.

Let’s take an example using a switch case:

PHP Variables Scope:

PHP variable scope is a part of a program that can be accessed or visible.

There are three types of Variable scope:

  1. Local Scope
  2. Global Scope

Local and Global Scope:

A variable declares inside the function is called Local Scope that accesses only inside the function.

Example:

A variable declares outside the function is called Global Scope that can be accessed inside the function by global keyword.

PHP Global scope variable also accesses by $GLOBALS array. It associates with the key of the name of the variable.

Returning Values from a Function

You can return value, array, or object by return keyword in the function and the return stops the execution of the function.

Example:

In the above example, the function is written for adding two numbers and returning the sum of two values($a, $b). Assigned the return value after calling the function to the $sum variable and it will show the following output:

Output:

Recursive Function in PHP

A recursive function is a function that calls itself continually until the terminating state arrives.

Let’s take an example:

In the above example, printing the table of 2 without using the PHP loop.

Output:

Predefined Functions in PHP:

PHP has many pre-defined functions which are called built-in functions.

You can check those functions here: https://www.php.net/manual/en/indexes.functions.php

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *