PHP Functions

Submitted by: 

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.

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.