PHP Functions
A function is a block of code with a name. You write it once and use it as many times as you like.
Built-in Functions
PHP already has thousands of functions, such as strlen(), date() and count(). In this lesson you will write your own.
Creating a Function
Example
<?php
function greet() {
echo "Welcome to Workownix!<br>";
}
greet();
greet();Welcome to Workownix! Welcome to Workownix!
The code inside the function only runs when you call it with greet().
Parameters
Parameters let you send values into a function:
Example
<?php
function greetStudent($name, $course) {
echo "Hello $name, welcome to the $course course.<br>";
}
greetStudent("Ali", "Web Development");
greetStudent("Ayesha", "Graphic Designing");Hello Ali, welcome to the Web Development course. Hello Ayesha, welcome to the Graphic Designing course.
Default Values
A parameter can have a default value, used when you do not pass one:
Example
<?php
function deliveryCharge($city = "Karachi") {
return $city === "Karachi" ? 150 : 300;
}
echo deliveryCharge() . "<br>";
echo deliveryCharge("Multan");150 300
Returning Values
return sends a value back to the code that called the function:
Example
<?php
function totalBill($price, $qty, $discount = 0) {
$total = $price * $qty;
return $total - ($total * $discount / 100);
}
$bill = totalBill(500, 3, 10);
echo "You pay Rs $bill";You pay Rs 1350
Type Declarations
Modern PHP lets you say which types a function accepts and returns. PHP then checks the values for you.
Example
<?php
declare(strict_types=1);
function average(int ...$numbers): float {
return array_sum($numbers) / count($numbers);
}
echo average(70, 80, 95);81.666666666667
int ...$numbers collects any number of integer arguments into an array. With strict_types=1, passing "70" (a string) would cause an error.
Use type declarations in real projects. They catch many mistakes early and make your code easier to read.
Named Arguments (PHP 8)
You can pass arguments by name, in any order:
Example
<?php
function makeLabel(string $text, bool $bold = false, string $color = "black"): string {
return "$text ($color" . ($bold ? ", bold" : "") . ")";
}
echo makeLabel("Sale", color: "red");Sale (red)
Arrow Functions
A short function for simple, one-line jobs:
Example
<?php
$addTax = fn($price) => $price * 1.18;
echo $addTax(1000);1180
Variable Scope
Variables created inside a function exist only inside it. Variables from outside are not visible inside, unless you pass them as parameters.
| Variable | Where it can be used |
|---|---|
| Local (made inside a function) | Only in that function |
| Global (made outside) | Outside functions, or passed in as a parameter |
Exercise
Exercise
What keyword sends a value back from a function?
