← 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!
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Closes Nov 30

Enroll in Backend Development

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account