Skip to main content

PHP Functions

Functions play an important role in any programming languages. It allows you to organize your code in smaller part.

A function can be called repeatedly in your program and can return or not return any value.

There are more than 1,000 built-in functions in PHP and you can also create your own function.

Here’s the syntax of a user defined function:

function functionName()
    your code or statement here;

When you name a function, make sure that it reflects the code that you write so you will know its purpose.

Let’s create a sample that will print the Hello World! string.

  1. <?php
  2. function printMsg()
  3. {
  4. echo "Hello world!";
  5. }
  7. printMsg(); // call printMsg function
  8. ?>

The above code simply prints the string “Hello World!” by calling its function name called printMsg. This function does not return any value.

Now let’s create a function that return a value with arguments.

  1. <?php
  2. function calculate($number1, $number2)
  3. {
  4. return $number1 + $number2;
  5. }
  7. calculate(1, 1); // call calculate function
  8. ?>

The code above simply pass the parameter to calculate function using an argument $number1 and number2, then it returns a value by adding the two variables.


Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.


1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.