PHP Functions

0 0
Read Time:1 Minute, 31 Second

PHP Functions

PHP function is a piece of code that can be reused many times. It can take input as argument list and return value. There are thousands of built-in functions in PHP.

The real power of PHP comes from its functions.

Advantage of PHP Functions

Code Reusability: PHP functions are defined only once and can be invoked many times, like in other programming languages.

Less Code: It saves a lot of code because you don’t need to write the logic many times. By the use of function, you can write the logic only once and reuse it.

Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow of the application because every logic is divided in the form of functions.

PHP Function is divided in two groups:

1. PHP Built-in Functions

PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.

Please check out PHP reference for a complete overview of the PHP built-in functions.

2. PHP User Defined Functions

Besides the built-in PHP functions, it is possible to create your own functions.

  • A function is a block of statements that can be used repeatedly in a program.
  • A function will not execute automatically when a page loads.
  • A function will be executed by a call to the function.

How to create User-Defined Function in PHP?

A user-defined function declaration starts with the keyword function:

Syntax:

function functionName() {
  code to be executed;
}

Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive.

W3Schools

Tip: Give the function a name that reflects what the function does!

W3Schools

Example:

<?php
function writeMsg() {
  echo "Hello world!";
}

writeMsg(); // call the function
?>
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Comment