Retrieve the current PHP version as an integer

Amit Merchant · July 25, 2022 ·

Sometimes, when working on a feature that is tightly coupled with a certain version of the language, it’s important to check which version you’re running on your server.

For instance, if you want to use Enums in PHP, it’s important that you’re running PHP 8.1 or higher.

If we want to check that, we can do that by using the PHP_VERSION_ID constant. The constant represents the current PHP version as an integer. This is especially useful when you want to do a version comparison.

Note: PHP_VERSION_ID is available as of PHP 5.2.7

So, for example, here in one of the PRs in Laravel, the author is checking whether the current version PHP 8.1 or higher… and based on that includes the enum file like so.

if (PHP_VERSION_ID >= 80100) {
    include 'Enums.php';
}

This is particularly handy in scenarios where you know your application may run on multiple PHP versions and enable certain functionalities for certain PHP versions.

To retrieve PHP version as a string, you can use the PHP_VERSION constant that gives the version in form of “major.minor.release[extra]” notation.

Learn the fundamentals of PHP 8 (and 8.1), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?