Labs ICT
โญ Pro Login

Functions

Functions are reusable blocks of code. You define them once and call them whenever you need. They keep your code organized, reduce repetition, and make your programs easier to read and debug.

PHP has hundreds of built-in functions. But the real power comes from writing your own.

Defining Functions

Use the function keyword, followed by a name, parentheses for parameters, and curly braces for the body. Function names should describe what the function does โ€” getUserEmail(), calculateTotal(), validateInput().


<?php
function greetUser() {
  echo "Welcome to LabsICT!";
}

greetUser();
?>
    
Try it Yourself โ†’

Parameters and Arguments

Parameters are variables listed in the function definition. Arguments are the actual values you pass when calling the function. You can pass as many parameters as you need, separated by commas.


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

greet("Bilal");
greet("Aisha");
?>
    

Return Values

Functions can return values using the return keyword. Once a function returns, it stops executing and the value is sent back to where the function was called. Functions without a return return NULL.


<?php
function add($a, $b) {
  return $a + $b;
}

$result = add(5, 3);
echo $result;  // 8

function formatName($first, $last) {
  return "$first $last";
}

echo formatName("Bilal", "Idris");
?>
    

Default Arguments

You can set default values for parameters. If the caller doesn't provide an argument, the default is used. Defaults must come after required parameters.


<?php
function makeGreeting($name, $greeting = "Hello") {
  return "$greeting, $name!";
}

echo makeGreeting("Bilal");          // Hello, Bilal!
echo makeGreeting("Aisha", "Hi");    // Hi, Aisha!
?>
    

Type Declarations (PHP 7+)

You can specify the expected type of parameters and return values. PHP will throw an error if the types don't match. This makes your code more predictable and catches bugs early.


<?php
function multiply(int $a, int $b): int {
  return $a * $b;
}

echo multiply(4, 5);    // 20
echo multiply(4, "5");  // 20 โ€” string "5" is coerced to int

function getDiscount(float $price): string {
  return number_format($price * 0.9, 2);
}

echo getDiscount(100.00);
?>
    

๐Ÿงช Quick Quiz

What is the correct way to define a function named greet that accepts one parameter?