Explain User-Defined Functions in PHP with Examples ?

A user-defined function is a block of code created using the function keyword.
You write the function once and call it multiple times throughout your program.

Example:

function sayHello() {
    echo "Hello from a user-defined function!";
}

Why Use User-Defined Functions?

  • Avoids repeating the same code
  • Increases readability and organization
  • Makes maintenance easier
  • Helps modularize large programs
  • Promotes reusability

Syntax for User-Defined Functions

function functionName() {
    // statements to execute
}

Function names should be meaningful and follow a clear naming pattern.


Example: Simple User-Defined Function

function greet() {
    echo "Welcome to PHP Learning!";
}

greet();

Function With Parameters

You can pass values to functions using parameters.

function greetUser($name) {
    echo "Hello, $name!";
}

greetUser("Sagar");

Function With Return Value

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

$result = add(5, 10);
echo $result; // 15

Function With Default Parameters

function welcome($name = "Guest") {
    echo "Welcome, $name!";
}

welcome(); // Welcome, Guest!

Function With Multiple Parameters

function calculateArea($length, $width) {
    return $length * $width;
}

echo calculateArea(10, 5);

Using Functions Across Files (Reusability)

You can store functions in a separate file and include them in multiple PHP scripts.

Example:

// functions.php
function sayHi() {
    return "Hi there!";
}

// main file
include "functions.php";
echo sayHi();

Best Practices for User-Defined Functions

  • Use meaningful names
  • Keep functions short and focused
  • Write reusable and modular code
  • Add comments when needed
  • Avoid global variables inside functions

Citations

🔗 View other articles about PHP:
http://savanka.com/category/learn/php/

🔗 External PHP Documentation:
https://www.php.net/manual/en/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *