5 Things you might not know about PHP
Even after years of professional PHP development, you might not know some interesting features of modern PHP (i will consider PHP 8.1 in this topic). You can get stuck on a legacy project, work primarily with your own code, and skip PHP release notes — there are different ways to skip new (or even old) excellent points of PHP usage.
Today I will tell you about five interesting (in my opinion) things you could want to know.
- First-class Callable Syntax
PHP got this feature only in the 8.1 version, so you easily could skip it if you are not a big fan of release-notes reading (which is a significant omission).
To be short — you can pass any function or method as a variable. Just call it with “…” instead of arguments.
Pretty nice and more readable, isn’t it? :) You can do it even with built-in PHP functions:
2. Null Coalescing Assignment Operator
A pretty common task in data processing is filtering null variables and replacing them with some defaults. PHP has a special operator used to reduce the number of conditions in your code
Little bit artificial example:
It’s not a significant improvement, but it makes your code shorter and cleaner.
3. Array destruction in the foreach loop
Sometimes our data is not well-structured (especially in tasks like CSV parsing), and we should handle the data using number indexes like $data[0], $data[1], etc. Good news — there is a prettier way!
Array destruction is quite an old PHP feature, but when I met it right in the foreach definition — I was surprised; I had never thought about this way of destruction usage.
4. Multiple arguments of “isset” function
It’s written in the official docs, but who does read it, right? ;)
To be short: you can pass multiple args to “isset” functions, and you will get “true” only if all that args are set.
Short example:
5. New method “array_is_list”
PHP 8.0 brought us many lovely things, one of which is this function. Now you can get to know if you have a list or a map in a variable without manual checking its keys. This problem got 300K+ views on StackOverflow, and now there is a built-in method for this — array_is_list!
Not sure if it’s necessary to show an example here, but let’s do that
That’s all for today! I will happily see you in the comments if you learned something new today!