Course Content
About Lesson

What is a function in PHP?

Functions are blocks of reusable code that perform a specific task. PHP has many built-in functions, and you can also create your own (called user-defined functions).

ow to create a user-defined function?

Syntax:

function functionName() {
// code to be executed
}

Example:

PHP
<?php
function greet() {
  echo "Hello, welcome to PHP!";
}

greet(); // Call the function
?>

Function with parameters

Syntax:

function functionName($param1, $param2) {
  // code using $param1 and $param2
}

Example:
PHP
<?php
function add($a, $b) {
  echo $a + $b;
}

add(5, 10); // Outputs: 15
?>

Function with return value

Example:

PHP
<?php
function multiply($x, $y) {
  return $x * $y;
}

$result = multiply(4, 3);
echo $result; // Outputs: 12
?>

Default parameter values

Example:

PHP
<?php
function greetUser($name = "Guest") {
  echo "Hello, $name!";
}

greetUser();       // Outputs: Hello, Guest!
greetUser("John"); // Outputs: Hello, John!
?>

Built-in PHP functions (Examples)

FunctionPurpose
strlen()Get the length of a string
strtolower()Convert to lowercase
strtoupper()Convert to uppercase
array_push()Add items to an array
count()Count elements in an array
date()Get current date/time

Example:

PHP
<?php
echo strlen("PHP"); // Outputs: 3
?>