Menu

Functions in PHP

  • Functions in PHP is divided into two
    1. Built-in Functions
    2. User-Defined Functions

PHP Built-in Functions

  • PHP has over more than 1000+ inbuilt functions. 
  • The inbuilt functions in PHP can be called directly or indirectly.

PHP User Defined Functions

  • It is possible to create your own user-defined functions in PHP.
  • A function is a block of statements that will execute a task.
  • A function will not execute directly in the program when a page loads.
  • The function will execute when a call to the function happens.

PHP User-defined function rules

  • A function must start with an underscore or letter.
  • Function names are not case sensitive

Create a user-defined function in PHP

Syntax:

      function nameOfTheFunction() {
	    //code
	  }

Example:

      <?php
        function testFunction($address) {
            echo "$address<br>";
        }

        testFunction("Test1");
        testFunction("Test2");
        testFunction("Test3");
        testFunction("Test4");
        testFunction("Test4");
     ?>

PHP Function Arguments

  • An argument is like a variable and it consists of information.
  • The information can pass as an argument in PHP.
  • Arguments specified inside the function and after the parenthesis.
  • Arguments are separated by a comma and you can call the number of arguments you needed.
       <!DOCTYPE html>
       <html>
       <body>

       <?php
       function myAddress($address) {
           echo "$address<br>";
       }

       function myName($name1,$name2) {
           echo "$name1<br>$name2";
       }

       myAddress("Address 1"); //Single Argument
       myName("Test1", "Test1"); //Multiple Argument
       ?>

      </body>
      </html>