A function is a named block of code that can be run as many times as needed. It is also called a subroutine. Instead of repeating the same piece of code in different parts of the program, you can simply define it as a function and call it by name. This helps reduce the amount of code and makes it more understandable and easier to maintain.
Why are functions needed?
Imagine that you are writing code that performs the same actions in several places. Copying this code every time is inefficient. Instead, it is easier to write a function once and then simply call it when needed. This is especially useful if you need to make changes in the future — then you only have to modify the code in one place.
What types of functions are there?
There are two main types of functions:
- Built-in functions — pre-created in the PHP language itself. They are ready to use and cover a wide variety of tasks, from working with strings to interacting with databases.
- User-defined functions — created by the programmer themselves to solve specific tasks in the project.
How does a function work?
Working with a function involves two steps:
- Declaration — this is the stage when you give the function a name and specify what data it will accept.
- Calling — the moment when you use an already created function to get the desired result.
Arguments and return values
A function can receive data as “input” — these are called arguments. For example, if a function needs to check whether a year is a leap year, the year is passed to it as an argument.
After performing its actions, the function can return a result — for example, “yes” or “no,” ‘true’ or “false.” This value is returned to the part of the code where the function was called.
Scope
It is important to remember that variables declared inside a function are not accessible from outside. Conversely, variables created outside a function cannot be used directly inside it. To “insert” data into a function, you need to use arguments.
Where to practice?
The best way to understand how functions work is through practice. Online trainers and sandboxes for PHP are suitable for this — they allow you to try out code directly in your browser.