You can think of a function as a machine. A machine takes the raw materials you feed it and works with them to achieve a purpose or to produce a product. A function accepts values from you, processes them, and then performs an action (printing to the browser, for example), returns a new value, or both.
A function is a self-contained block of code that can be called by your scripts. When called, the function's code is executed. You can pass values to functions, which will then work with them. When finished, a function can pass a value back to the calling code.
1). Creating Your PHP Functions
2). Calling Your PHP Functions
3). Use Parameters - Functions
4). Returning Values - Functions
The general way of defining a function is
With a properly formatted function in place, we can now fill in the code that we want our function to execute. Do you see the curly braces in the above example "{ }"? These braces define where our function's code goes. The opening curly brace "{" tells php that the function's code is starting and a closing curly brace "}" tells PHP that our function is done!
PHP Example:-
Now that you have completed coding your PHP function, it's time to put it through a test run. Below is a simple PHP script. Let's do two things: add the function code to it and use the function twice.
PHP Example:-
Your out put is HELLO!
Go TopIf we were to use parameters, then we would be able to add some extra functionality! A parameter appears with the parentheses "( )" and looks just like a normal PHP variable. Let's create a new function that creates a custom greeting based off of a person's name. Our parameter will be the person's name and our function will concatenate this name onto a greeting string. Here's what the code would look like.
PHP Example:-
Your output is Hello Raj!
Go TopA function can return a value using the return statement in conjunction with a value. The return statement stops the execution of the function and sends the value back to the calling code.
PHP Example:-