PHP Functions
A function is a reusable block of code designed to perform a specific task.
What is it?
A function is a reusable block of code designed to perform a specific task.
Why do we use it?
Functions reduce repetition and make applications easier to maintain.
How does it work?
A function is defined once and can be called many times with different values.
Syntax
function functionName($parameter) {
return $value;
}
Example
<?php
function add($a, $b) {
return $a + $b;
}
echo add(10, 20);
?>
Example Explained
More Examples
<?php function greet($name) { return "Hello " . $name; } echo greet("Aman"); ?>
⚠️ Important Rules
Use meaningful function names and keep functions focused.
❌ Common Mistakes
Forgetting return or passing incorrect arguments.
🌍 Real-World Use
Functions organize business logic in large applications.
📝 Practice Exercise
Create functions for total, percentage, grade and discount.
💻 Try It Yourself
Write and run this PHP lesson inside the AIFA Coding Lab.