Php

Types of Functions (User-Defined and System-Defined)

Types of Functions in PHP


✅ 1. User-Defined Functions

These are functions you create yourself to organize and reuse code.

Syntax:

php
function functionName($parameter1, $parameter2) {
// Code to execute
return $something; // optional
}

✅ Example:

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

greet("Alice"); // Output: Hello, Alice!

When to Use:

  • When a block of code is repeated often

  • For better organization and readability

  • To handle specific logic (e.g. calculations, validations)


✅ 2. System-Defined (Built-in) Functions

These are predefined functions provided by PHP. You can use them directly without defining them.


Examples:

Category Function Description
String strlen() Returns length of a string
Array array_push() Adds item to end of an array
Math round() Rounds a number
Date/Time date() Formats date and time
File fopen() Opens a file
Misc isset() Checks if a variable is set

✅ Example:

php
$name = "Jonathan";
echo strlen($name); // Output: 8

Comparison Table

Feature User-Defined System-Defined (Built-in)
Who defines it? You (the programmer) PHP itself
Customizable? Yes No (fixed behavior)
Usage Must be declared before use Can be used anytime
Examples greet(), calculateSum() strlen(), array_push(), date()

Sample Use Case: Mixing Both

php
function calculateDiscount($price, $discount) {
$final = $price - ($price * $discount / 100);
return round($final, 2); // using built-in round()
}

echo calculateDiscount(100, 15); // Output: 85.00

Leave a Reply

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