php language basics

Functions

A function is a named block of code that does one job. You give it input through parameters, it performs a small piece of work, and it can give a value back with return.

Functions matter because they let you name repeated logic. Instead of copying the same formatting, calculation, or validation code into several places, you put the rule in one function and call it wherever it is needed.

A Small Function

PHP example
<?php

function formatFullName(string $firstName, string $lastName): string
{
    return trim($firstName) . ' ' . trim($lastName);
}

echo formatFullName(' Ada ', ' Lovelace ') . "\n";

// Prints:
// Ada Lovelace

$firstName and $lastName are parameters. The values passed into the function are arguments. The return statement sends the finished string back to the caller.

The type declarations say this function expects strings and returns a string. They make the contract easier to read and easier for tools to check.

Returning Is Not Printing

A function that returns a value is easier to reuse than a function that prints directly.

PHP example
<?php

function formatPrice(int $cents): string
{
    return '£' . number_format($cents / 100, 2);
}

$label = formatPrice(1299);

echo "Price: {$label}\n";

// Prints:
// Price: £12.99

formatPrice() does not decide where the result goes. The caller can echo it, put it into an email, return it in JSON, or compare it in a test. That separation is a practical habit in professional PHP code.

Default Arguments

A parameter can have a default value. The default is used when the caller does not provide that argument.

PHP example
<?php

function greet(string $name, string $prefix = 'Hello'): string
{
    return "{$prefix}, {$name}";
}

echo greet('Amo') . "\n";
echo greet('Amo', 'Welcome back') . "\n";

// Prints:
// Hello, Amo
// Welcome back, Amo

Defaults are useful for simple options. Avoid hiding important business decisions in defaults that callers may not notice.

Guarding Invalid Input

Functions are boundaries. If a function cannot work with a value, reject it early.

PHP example
<?php

function calculateTaxCents(int $subtotalCents, float $rate): int
{
    if ($subtotalCents < 0) {
        throw new InvalidArgumentException('Subtotal cannot be negative.');
    }

    if ($rate < 0) {
        throw new InvalidArgumentException('Tax rate cannot be negative.');
    }

    return (int) round($subtotalCents * $rate);
}

echo calculateTaxCents(1000, 0.2) . "\n";

// Prints:
// 200

The guard clauses make invalid input explicit. This is better than allowing a bad value to flow through a calculation and become a harder bug later.

Function Names

Name functions after the job they do. formatFullName(), calculateTaxCents(), and isEligibleForFreeShipping() are clearer than names such as process(), handleData(), or doStuff().

A good function is usually small enough to explain in one sentence. If you need "and then" several times to describe it, it may be doing too much.

Scope

Variables created inside a function are local to that function.

PHP example
<?php

function buildLabel(string $sku): string
{
    $prefix = 'SKU';

    return "{$prefix}: {$sku}";
}

echo buildLabel('ABC-123') . "\n";

// Prints:
// SKU: ABC-123

The $prefix variable exists inside buildLabel(). Code outside the function should not rely on it. This keeps functions from accidentally changing unrelated code.

Common Mistakes

Do not write functions that depend on hidden global variables when a parameter would make the dependency clear.

Do not mix too many responsibilities. A function that validates input, updates a database, sends an email, and prints HTML is hard to test and hard to reuse.

Do not ignore return values. If a function returns something important, store it, print it, or pass it somewhere deliberately.

What You Should Be Able To Do

After this lesson, you should be able to:

  • define a function with parameters and a return type;
  • call a function with arguments;
  • explain the difference between returning and printing;
  • use a default argument for a simple option;
  • add guard clauses for invalid input;
  • choose clear function names;
  • avoid hidden dependencies on global state.

Practice

Task: Format Full Name

Task

Write a function named formatFullName() that accepts $firstName and $lastName as strings and returns a cleaned full name.

The function should:

  • trim spaces from both names;
  • join the names with one space;
  • return the string instead of printing inside the function.

Call the function with ' Ada ' and ' Lovelace ' and print the result.

Hints

  • Use trim().
  • Use a string return type.
  • Keep the echo outside the function.
Show solution

Solution

PHP example
<?php

function formatFullName(string $firstName, string $lastName): string
{
    return trim($firstName) . ' ' . trim($lastName);
}

echo formatFullName(' Ada ', ' Lovelace ') . "\n";

// Prints:
// Ada Lovelace

Explanation

The function returns the formatted name, so the caller decides what to do with it. That makes the function reusable in HTML, JSON, email, tests, or CLI output.

Task: Predict Default Argument

Task

Before running the code, predict what each line prints.

PHP example
<?php

function buildGreeting(string $name, string $prefix = 'Hello'): string
{
    return "{$prefix}, {$name}";
}

echo buildGreeting('Mina') . "\n";
echo buildGreeting('Mina', 'Welcome back') . "\n";

Then run the code and compare the real output with your prediction.

Hints

  • The default value is used only when the caller omits that argument.
  • Passing the second argument replaces the default.
Show solution

Solution

PHP example
<?php

function buildGreeting(string $name, string $prefix = 'Hello'): string
{
    return "{$prefix}, {$name}";
}

echo buildGreeting('Mina') . "\n";
echo buildGreeting('Mina', 'Welcome back') . "\n";

// Prints:
// Hello, Mina
// Welcome back, Mina

Explanation

The first call omits the second argument, so PHP uses the default prefix Hello. The second call supplies Welcome back, so the default is not used.

Task: Write Tax Function

Task

Write a function named calculateTaxCents() that accepts:

  • $subtotalCents as an integer;
  • $rate as a float.

The function should:

  • throw InvalidArgumentException if $subtotalCents is negative;
  • throw InvalidArgumentException if $rate is negative;
  • return the rounded tax amount in cents as an integer.

Call it with 2500 and 0.2, then print the result.

Hints

  • Use round() before casting to int.
  • Keep validation inside the function.
  • Return the tax amount; print it outside the function.
Show solution

Solution

PHP example
<?php

function calculateTaxCents(int $subtotalCents, float $rate): int
{
    if ($subtotalCents < 0) {
        throw new InvalidArgumentException('Subtotal cannot be negative.');
    }

    if ($rate < 0) {
        throw new InvalidArgumentException('Tax rate cannot be negative.');
    }

    return (int) round($subtotalCents * $rate);
}

echo calculateTaxCents(2500, 0.2) . "\n";

// Prints:
// 500

Explanation

The function validates its own inputs before calculating. That makes the function safer to reuse because callers cannot accidentally pass a negative subtotal or tax rate without getting a clear error.