Back-End Development PHP basics

PHP functions

PHP functions are the real power of PHP . It has more than 1000 built-in functions.

PHP functions

  • Besides built-in functions, we can create our own function in PHP
  • When we want to execute a same block of code multiple times, function are used.
  • Functions are called by writing

Creating a User defined function

A user defined function is declared using fucntion keyword.

Syntax:

Example:


Output:

Hello !Scanfcode

We have created a function name writeMsg(); ,the opening brace ‘{‘ marks the begining of the function code and closing brace ‘}’ indicates the ending of the function code. The statement echo “Hello ! Scanfcode” is what this function does.To call the function just write the name.

PHP function arguments

Information can be passed to a function as an argument. Argument s are just like variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example illustrates the function writeName($wname), $wname is passed as an argument. The function prints the name passed to it.


Output:

Scanfcode
Code
PHP

Default arguments

The following example shows how to use a default parameter. If we call the function showAge() without arguments it takes the default value as argument:


Output:

20
18
10

Returning value

return keyword can be used in a function to return any value.


Output:

5+10=15
7+13=20
2+4=6