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. }
  6.  
  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. }
  6.  
  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.

Add new comment