"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."

Functions (Built-in & User-defined)

 

Functions in PHP are blocks of code designed to perform a specific task. They help make code reusable, organized, and easier to maintain. PHP provides built-in functions for common tasks, and also allows you to create your own user-defined functions.


Built-in Functions

PHP has hundreds of built-in functions that perform predefined operations such as string manipulation, mathematical calculations, and array handling.

Example (Built-in Functions):

<?php

// String length

echo strlen("Hello World"); // Outputs: 11

 

// Find maximum value in an array

echo max(10, 20, 30); // Outputs: 30

 

// Convert string to uppercase

echo strtoupper("php is awesome"); // Outputs: PHP IS AWESOME

?>


User-defined Functions

You can create your own functions to execute code whenever needed. This helps reduce repetition and makes programs easier to read.

Syntax:

function functionName($parameter1, $parameter2) {

    // Code to be executed

    return $result;

}

Example (User-defined Function):

<?php

function greet($name) {

    return "Hello, " . $name . "!";

}

 

echo greet("John"); // Outputs: Hello, John!

?>


Functions with Default Parameters

If a function parameter has a default value, it can be omitted when calling the function.

Example:

<?php

function welcome($name = "Guest") {

    return "Welcome, " . $name;

}

 

echo welcome(); // Outputs: Welcome, Guest

echo welcome("Sara"); // Outputs: Welcome, Sara

?>


Returning Values

Functions can return values to be used later in the program.

Example:

<?php

function add($a, $b) {

    return $a + $b;

}

 

$result = add(5, 10);

echo $result; // Outputs: 15

?>

 

Popular Posts

Operators (Arithmetic, Comparison, Logical)