Skip to main content
PHP Functions
Prepared By:-
Kale J. N.
Assistant Professor,
Computer Engineering,
Sanjivani College of Engineering, Kopargaon
Prepared By: Kale J. N.
1. Introduction to Functions in PHP
• A function is a reusable block of code that performs a specific task.
Prepared By: Kale J. N.
2. Syntax of Function
function functionName() {
// code to execute
}
• Example:
<?php
function greet() {
echo "Hello Students";
}
greet(); // Function call
?>
• Output:
• Hello Students
Prepared By: Kale J. N.
Types of Functions in PHP
• Built-in Functions
• User-defined Functions
• Keywords are NOT case-
sensitive
• ECHO "Hello";
• echo "Hello";
Prepared By: Kale J. N.
3.1 Built-in Functions
• Predefined functions provided
by PHP.
• Examples:
echo strlen("Hello"); // Length of
string
echo date("Y"); // Current year
echo sqrt(16); // Square root
•
Prepared By: Kale J. N.
3.2 User-defined Functions
• Functions created by
programmer.
function add() {
echo 5 + 10;
}
add();
Prepared By: Kale J. N.
4. Function with Parameters
• Parameters allow passing values
to a function.
• Syntax:
function functionName($param1,
$param2) {
// code
}
• Example:
<?php
function add($a, $b) {
echo $a + $b;
}
add(5, 10); // Output: 15
?>
Prepared By: Kale J. N.
5. Function with Return Value
Prepared By: Kale J. N.
• Instead of printing, function can
return value.
<?php
function add($a, $b) {
return $a + $b;
}
$result = add(5, 10);
echo $result; // 15
?>
•
6. Default Parameter Values
<?php
function greet($name = "Guest") {
echo "Hello " . $name;
}
greet(); // Hello Guest
greet("Jay"); // Hello Jay
?>
Prepared By: Kale J. N.