← PHP tutorial

PHP

Functions

Define a function with function name($params) { ... }, and return a value if it should produce one.

Example: a greeting function

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

  echo greet("Chidi");
?>
Hello, Chidi!

Note that variables interpolate inside the returned string exactly the same way they did in the Echo lesson — $name works inside a double-quoted string whether it's a top-level variable or, as here, a function parameter.

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

  echo greet("Chidi");
?>
Output
Hello, Chidi!