How to Create Function in PHP: Syntax and Examples
In PHP, you create a function using the
function keyword followed by the function name and parentheses. Inside the curly braces { }, you write the code that runs when the function is called.Syntax
To create a function in PHP, use the function keyword, then the function name, parentheses () for parameters, and curly braces { } to hold the code. The function name should be descriptive and follow naming rules (letters, numbers, underscores, no spaces).
- function: keyword to declare a function
- functionName: your chosen name for the function
- (): parentheses to hold parameters (optional)
- { }: curly braces to enclose the function code
php
function functionName() { // code to run }
Example
This example shows a simple function named greet that prints a greeting message when called.
php
<?php function greet() { echo "Hello, friend!"; } greet(); ?>
Output
Hello, friend!
Common Pitfalls
Common mistakes when creating functions in PHP include:
- Forgetting the
functionkeyword. - Missing parentheses
()after the function name. - Not using curly braces
{ }to enclose the function code. - Calling the function before it is defined in some cases (unless using PHP's function hoisting).
Here is an example of a wrong and right way:
php
<?php // Wrong way: missing parentheses // function sayHello { // echo "Hi!"; // } // Right way: function sayHello() { echo "Hi!"; } sayHello();
Output
Hi!
Quick Reference
Remember these tips when creating functions in PHP:
- Use
functionkeyword to start. - Name functions clearly and use lowercase with underscores if needed.
- Parentheses
()are required even if no parameters. - Curly braces
{ }must wrap the function code. - Call functions by their name followed by parentheses.
Key Takeaways
Use the
function keyword followed by the function name and parentheses to create a function.Always include curly braces
{ } to enclose the function's code block.Function names should be descriptive and follow PHP naming rules.
Call functions by their name with parentheses to run the code inside.
Avoid common mistakes like missing parentheses or curly braces.