PHP Functions

The real power of PHP lies in its functions, which simplify repetitive tasks and enhance program organization. PHP provides more than 1000 built-in functions, and you can also create your own.

Tutorials dojo strip



PHP Built-in Functions

PHP includes a vast library of built-in functions that can be directly invoked from a script to perform specific tasks. Check out a PHP function reference guide for a detailed list of these tools.




PHP User-Defined Functions

In addition to the built-in functions, PHP allows you to create custom functions tailored to your needs. Here’s what you need to know about user-defined functions:

  • A function is a reusable block of code that can be invoked multiple times within a program.
  • Functions do not execute automatically when a page loads. Instead, they must be explicitly called.
  • To execute a function, you simply invoke it using its name.




Creating a Function

To declare a user-defined function, use the function keyword followed by its name.

Example: Display a Motorcycle Brand

function showBrand() {
  echo "Welcome to Yamaha!<br>";
}

Explanation:

  • The function showBrand() outputs “Welcome to Yamaha!”.
  • Function names must start with a letter or an underscore and are not case-sensitive.
  • Always assign meaningful names to your functions, reflecting their purpose.




Calling a Function

To execute a function, call its name followed by parentheses.

Example: Call the Function

function showBrand() {
  echo "Welcome to Yamaha!<br>";
}

showBrand();




PHP Function Arguments

Functions can accept data in the form of arguments, which operate like variables. Arguments are specified in the parentheses following the function name.

Example: Display Motorcycle Owners

function motorcycleOwner($owner) {
  echo "$owner owns a Suzuki motorcycle.<br>";
}

motorcycleOwner("John");
motorcycleOwner("Sarah");
motorcycleOwner("Mike");

Explanation:

  • The function motorcycleOwner($owner) uses an argument $owner to personalize the output.

Example: Multiple Arguments

function motorcycleDetails($brand, $year) {
  echo "$brand was established in $year.<br>";
}

motorcycleDetails("BMW", "1916");
motorcycleDetails("Honda", "1946");
motorcycleDetails("Suzuki", "1909");

Explanation:

  • This function accepts two arguments: $brand (e.g., “BMW”) and $year (e.g., “1916”), and outputs their combination.




PHP Default Argument Values

You can define default values for function arguments. If no value is provided during the function call, the default value is used.

Example: Setting a Default Height

function setSeatHeight($height = 30) {
  echo "The seat height is $height inches.<br>";
}

setSeatHeight(35);
setSeatHeight(); // Uses the default value of 30
setSeatHeight(40);

Explanation:

  • When no argument is passed, $height defaults to 30.




PHP Functions – Returning Values

Functions can return values using the return statement.

Example: Calculate Total Mileage

function totalMileage($mileage1, $mileage2) {
  $total = $mileage1 + $mileage2;
  return $total;
}

echo "Total Mileage: " . totalMileage(120, 200) . " km<br>";
echo "Total Mileage: " . totalMileage(50, 75) . " km<br>";

Explanation:

  • The function calculates the total mileage by adding two numbers and returning the result.




Passing Arguments by Reference

By default, arguments are passed by value in PHP. Use the & symbol to pass arguments by reference, allowing modifications to the original variable.

Example: Adjust Price of a Motorcycle

function increasePrice(&$price) {
  $price += 500;
}

$price = 15000;
increasePrice($price);
echo "New price: $price<br>";

Explanation:

  • The increasePrice() function updates the original $price variable directly.




Variable Number of Arguments

You can use the ... operator to allow functions to accept an unknown number of arguments, creating a variadic function.

Example: Calculate Total Sales

function totalSales(...$sales) {
  $total = array_sum($sales);
  return $total;
}

echo "Total Sales: " . totalSales(1000, 2000, 1500, 3000) . "<br>";

Explanation:

  • The ...$sales gathers all passed arguments into an array for easy processing.




PHP Strict Typing

PHP 7 introduced strict typing, enabling you to enforce data types for function arguments and return values. Add declare(strict_types=1); at the start of the file to enable strict mode.

Example: Enforcing Integer Arguments

<?php declare(strict_types=1);

function calculateCost(int $price, int $discount) {
  return $price - $discount;
}

echo "Final Cost: " . calculateCost(15000, 2000) . "<br>";
?>

Explanation:

  • The function enforces integer arguments, ensuring no unexpected data types are used.
Tutorials dojo strip
Scroll to Top