What if you could write a piece of code once and use it anywhere without repeating yourself?
Why Function declaration and calling in PHP? - Purpose & Use Cases
Imagine you need to calculate the area of different rectangles in your PHP script. Without functions, you would have to write the same calculation code again and again for each rectangle.
Writing the same code repeatedly is slow and tiring. It's easy to make mistakes or forget to update all copies if the calculation changes. This wastes time and causes bugs.
Functions let you write the calculation once, give it a name, and then use that name whenever you need the result. This keeps your code clean, easy to read, and simple to fix or update.
$area1 = $width1 * $height1; $area2 = $width2 * $height2; $area3 = $width3 * $height3;
function calculateArea($width, $height) {
return $width * $height;
}
$area1 = calculateArea($width1, $height1);
$area2 = calculateArea($width2, $height2);
$area3 = calculateArea($width3, $height3);Functions let you reuse code easily, making your programs faster to write and simpler to maintain.
Think of a recipe you use often. Instead of rewriting it every time, you keep it in one place and follow it whenever you cook. Functions work the same way in programming.
Functions save time by avoiding repeated code.
They reduce errors by centralizing logic.
Calling functions makes code clearer and easier to manage.