PHP CHAPTER 19

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

PHP Syntax
function functionName($parameter) {
    return $value;
}
💻

Example

PHP Example
<?php

function add($a, $b) {
    return $a + $b;
}

echo add(10, 20);

?>
🔍

Example Explained

The function receives two values and returns their sum. add(10,20) calls the function.
🚀

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.

Open Coding Lab →