Functions in PHP

Introduction to Functions in PHP

Same like all other programming languages PHP also have functions. Functions are some part of the code which is written separately and by calling them we use that coding gain and again.

In PHP there are two types of functions:

  • User-defined function
  • Built-in function

User-Defined Functions:

In PHP as there is no concept of data type so while declaring function we have not to tell its data type or return type.

The function keywords indicate that it’s a function so in PHP functions are created followed by function keyword and after this functions name and then its parameter list and then the body.

Built-In Functions:

There is a collection of built-in functions in PHP. These functions are pre-defined by default in PHP and as in other languages we have to import or include libraries to use some function but in PHP all functions are available in all parts of the virtual directory, but they have some conditions like for using SQL function you must have an active database connection.

We already covered almost all important built-in function of MYSQLi and SQL.

Some other important functions are listed below with example:

include()

This function is used to include a file in another file. It’s same like in other languages we import some other files or libraries.

index.php

head.php

include_once()

This is same as include but if we include the same file two times include_once function ignores the duplicated file.

echo

This is used to print output. It has no return values. It can take multiple parameters as shown in the example.

print

It is also used to show output the main difference between echo and print is it has a return value, and it can’t take multiple parameters.

header

This function is used to redirect the execution to some other file. This function takes the location of the targeted file.

isset()

This function is used to check the required property is set or not. It takes one single parameter.

empty()

It is used to check either the variable is empty or not.

is_null()

This function checks the variable in parameter is null or not.

mail()

This function is used to send a mail in PHP.

Syntax

mail (receiver, subject, your message);

Example

wordwarp()

This function is used to wrap the text line in PHP. It will cut or break the line into new line when some specifically given length is reached.

explode()

This function breaks a PHP string into a string array.

htmlspecialchars()

This function converts HTML tags special characters to their XML code. It will convert the predefined characters which are used as start and end of HTML tags “<” (less than) and “>” (greater than) to HTML entities.

The predefined characters are:

  • & (ampersand) becomes &amp;
  • ” (double quote) becomes &quot;
  • ‘ (single quote) becomes &#039;
  • < (less than) becomes &lt;
  • > (greater than) becomes &gt;

For more PHP pre-defined function