PHP Functions

Why should we use functions?

  • Organize our code
  • Avoid repetive code
  • Break complex code into logical chunks

Built-in functions

Much of the power of PHP comes from its built-in functions.

echo strrev(" .dlrow olleH");
echo str_repeat("Hip ", 2);
echo strtoupper("hooray!");
echo strlen("intro");
echo "\n";

/* Output:
Hello world.
Hip Hip

The function_exists() function is used to check if a function already exists or not.

if (function_exists("array_combine")){
    echo "Function exists";
} else {
    echo "Function does not exist";

phpinfo() prints out the internal configuration capabilities of your particular PHP installation.


Define your own function

We can use the function keyword to define a function.

We name the function and take optional argument variables. The body of the function is in a block of code { }

function greet() {
    print "Hello\n";

Function names

  • Similar to variable names but do not start with a dollar sign
  • Start with a letter or underscore - consist of letters, numbers, and underscores ( _ )
  • When naming a function, we should avoid built-in function names
  • Although it’s not case sensitive but don’t take advantage of this

Return values

Often a function will take its arguments, do some computation, and return a value to be used as the value of the function call in the calling expression.

The return keyword is used for this.

function greeting() {
    return "Hello";
print greeting() . " Anna\n";
print greeting() . " John\n";
// Output:
// Helo Anna
// Hello John