A function in PHP is a block of reusable code that performs a specific task. Functions help reduce repetition and make code more organized.
<?php
function sayHello() {
echo "Hello, World!";
}
sayHello(); // Calling the function
?>
👉 Explanation:
function keyword.Parameters allow you to pass values into a function.
<?php
function greet($name) {
echo "Hello, " . $name;
}
greet("Samir");
?>
👉 Key Points:
If no value is passed, default values are used.
<?php
function welcome($name = "Guest") {
echo "Welcome, " . $name;
}
welcome(); // Output: Welcome, Guest
welcome("Samir"); // Output: Welcome, Samir
?>
Functions can return data to the place where they are called.
<?php
function add($a, $b) {
return $a + $b;
}
$result = add(10, 20);
echo $result; // 30
?>
👉 Explanation:
return sends a value back from the function.You can specify the data type for parameters and return values.
<?php
function multiply(int $a, int $b): int {
return $a * $b;
}
echo multiply(5, 3);
?>
Variables inside a function are local and cannot be accessed outside.
<?php
$x = 100;
function test() {
$y = 50;
echo $y;
// echo $x; // Error: cannot access global variable directly
}
test();
?>
<?php
$a = 10;
$b = 20;
function sum() {
global $a, $b;
echo $a + $b;
}
sum();
?>
Static variables retain their value even after the function ends.
<?php
function counter() {
static $count = 0;
$count++;
echo $count . "<br>";
}
counter(); // 1
counter(); // 2
counter(); // 3
?>
👉 Summary:
PHP offers hundreds of built-in functions that make development easier. You do not need to create them — just call them directly.
<?php
echo strlen("Hello"); // String length
echo strrev("Hello"); // Reverse a string
echo strtoupper("hello"); // Convert to uppercase
echo rand(1, 100); // Generate random number
echo round(3.7); // Round a number
echo date("Y-m-d"); // Current date
?>
👉 Popular Categories of Built-in Functions:
strlen(), str_replace(), strpos()count(), array_merge(), in_array()abs(), round(), rand()date(), time()file_get_contents(), fopen()isset(), empty(), var_dump()👉 Notes: