Control Flow & FunctionsCore· 35 min read

Functions

Reusable blocks of code with parameters and return values.

What you will learn

  • Define and call functions
  • Pass parameters and return values

Define and call

A function is a named, reusable block of code. You define it once with the function keyword, then call it by name as many times as you like. A parameter (here $name) is an input you hand in; return sends a value back to whoever called it.

A function with a parameter and return
<?php
  function greet($name) {
    return "Hello, $name!";
  }
  echo greet("Asha");      // Hello, Asha!
  echo greet("Ravi");      // Hello, Ravi!
?>

The function greet($name) { ... } block defines the recipe but does not run yet. It runs only when called: greet("Asha") runs the body with $name set to "Asha" and returns "Hello, Asha!", which echo then prints. Calling it again with "Ravi" reuses the exact same code with a different input.

Note: Output (in the browser): Hello, Asha!Hello, Ravi! The same function produced two different results just by passing a different value in. Write the logic once, reuse it forever.

Functions are not limited to text — they can do calculations and return the answer. This one adds two numbers:

Returning a value
<?php
  function add($a, $b) {
    return $a + $b;
  }
  echo add(5, 3);   // 8
?>

Here add takes two parameters, $a and $b. The call add(5, 3) sends 5 into $a and 3 into $b (in order), the function returns their sum, and echo prints it.

Note: Output (in the browser): 8 return hands the result back so you can echo it, store it in a variable, or feed it into another function. That is the difference from echo inside the function, which would only print and give nothing back.

Tip: Functions keep code DRY (Do not Repeat Yourself). If you write the same lines twice, make a function.

Q. Which keyword sends a value back from a PHP function?

Answer: return sends a result back to the caller. echo prints directly to the page.

✍️ Practice

  1. Write a function that returns the square of a number.
  2. Write a function that returns the total of a price and tax.

🏠 Homework

  1. Write a function that takes a name and returns a full HTML greeting card string.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →