Functions
8 min · PHP
Package code under a name so you can reuse it.
Enemy 1 of 5
Defining and calling a function
As programs grow, you'll find yourself wanting to run the same logic in more than one place — squaring a number, formatting a name, validating input. A function lets you write that logic once, give it a name, and then call it by name wherever you need it, instead of retyping (or copy-pasting) the same code repeatedly.
Beyond saving typing, functions make programs easier to reason about: once you trust that double($n) correctly doubles a number, you can use double(5) anywhere without re-reading its internals every time, the same way you don't re-derive how a calculator's multiply button works each time you press it.
You define a function with the function keyword, followed by a name and a parameter list in parentheses. Parameters are placeholder variables that receive whatever values are passed in when the function is called — in function double($n), $n is a parameter that will hold whatever number you pass to double(...) at call time.
Inside the function body, return hands a value back to whoever called the function, and immediately stops the function from running any further code after it. This is different from echo, which prints text but doesn't give the calling code anything to work with programmatically — echo double(5) works because double(5) first returns a value (10), and only then does echo print that returned value.
A function that never executes a return statement implicitly returns null (PHP's "nothing here" value) once it reaches its closing brace — a subtle detail that matters if you ever forget the return keyword and wonder why your result is empty.
Loading editor...