Functions in PHP – Reusable Code Blocks
What is a Function in PHP?
A function is a block of code that performs a specific task and can be reused wherever needed.
Instead of repeating the same lines again and again, you can wrap them in a function and call that function when required. This improves code reusability, readability, and maintainability.
Defining a Function in PHP
Syntax:
function functionName() {
// code to execute
}
Example:
<?php
function greetUser() {
echo "Hello, welcome to ScriptBuzz!";
}
greetUser(); // Call the function
?>
Output:
Hello, welcome to ScriptBuzz!
Function with Parameters
You can pass values to a function using parameters (also called arguments). Parameters are specified inside the parentheses.
Example with One Parameter:
<?php
function greet($name) {
echo "Hello, $name!";
}
greet("Emma");
?>
Output:
Hello, Emma!
Multiple Parameters:
<?php
function displayUserInfo($name, $age) {
echo "$name is $age years old.";
}
displayUserInfo("Jay", 28);
?>
Function with Return Value
Instead of printing the result, you can return it for further use.
Example:
<?php
function getTotal($price, $tax) {
$total = $price + ($price * $tax / 100);
return $total;
}
$finalAmount = getTotal(100, 18);
echo "Total Amount: $finalAmount";
?>
Output:
Total Amount: 118
Returning values is useful for calculations, validations, and any function whose result you want to reuse.
Default Values in Functions
You can provide default values to parameters. If no value is passed, the default is used.
Example:
<?php
function greet($name = "Guest") {
echo "Hello, $name!";
}
greet(); // Output: Hello, Guest!
greet("Script"); // Output: Hello, Script!
?>
Function Scope – Local vs Global Variables
Local Variables:
Declared inside a function and accessible only within that function.
function testScope() {
$x = 5; // Local to testScope()
echo $x;
}
Global Variables:
Declared outside a function. To use them inside a function, declare them with the global
keyword.
<?php
$x = 10;
function showValue() {
global $x;
echo $x;
}
showValue(); // Output: 10
?>
Real-World Examples of PHP Functions
Example 1: Calculate Discount
function calculateDiscount($amount, $discountPercent) {
return $amount - ($amount * $discountPercent / 100);
}
echo "After Discount: " . calculateDiscount(500, 20);
Example 2: Convert Temperature
function celsiusToFahrenheit($c) {
return ($c * 9 / 5) + 32;
}
echo celsiusToFahrenheit(30); // Output: 86
Common Mistakes to Avoid
- Declaring the same function name more than once
- Forgetting parentheses when calling a function
- Using variables outside of their scope
- Forgetting the
return
keyword when needed
Best Practices for Functions
- Name functions clearly (e.g.,
calculateTotal
,sendEmail
) - Keep functions short and focused (one job only)
- Use default values to make functions more flexible
- Always return values if you need to reuse results
- Avoid relying heavily on global variables
otes:
- A function is a reusable block of code that simplifies programming
- Use parameters to pass values and
return
to send results back - Functions can have optional/default parameters
- Scope is important: local variables stay within the function
- Functions improve modularity and reduce code repetition
Practice Tasks
Task 1: Greeting Function
Create a function greetUser()
that accepts a name and displays:
Hello, [Name]! Welcome to ScriptBuzz.
Task 2: Multiply Function
Write a function that multiplies two numbers and returns the result. Test with 5
and 4
.
Task 3: Percentage Calculator
Create a function getPercentage($score, $total)
that returns the percentage.
💡 Explore More PHP Learning Tools & Resources
PHP Practice Quiz
Test your PHP skills with real coding questions and scoring.
PHP Interview Questions
Prepare for interviews with common PHP questions and answers.
Educational AI Tutor
Ask PHP questions and get instant AI-powered explanations.
Question Generator
Auto-generate PHP interview questions for quick practice.