Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 6 / 68

Writing a Function

In this lesson you will learn how to define a function in PHP so you can reuse the same logic over and over. This is for anyone searching for "PHP function how to create".

function defines a function and return hands back a result. Bundling frequently used work under a name means you only have to call it to run it. Change the arguments and the same logic gives you a different result each time.

The sample code defines a greet function that takes a $name argument and returns a greeting with return. Notice how echo greet("Bob"); prints the returned value directly.

A common stumbling block for beginners is forgetting return, which leaves the function's result unusable. Printing with echo and handing back a value with return serve different purposes, and you need to understand both.

You can also add type declarations, and stating the types of the arguments and the return value makes for safer code. Writing function greet(string $name): string tends to be valued more highly the larger the project gets.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)