PHP Version Compatibility

PHP is in an ongoing process of development, and there are multiple versions. If you need to check whether a particular function is available to your code, you can use the function_exists function, which checks all predefined and user-created functions.

Example 5-9 checks for the function array_combine, which is specific to PHP version 5.

Example 5-9. Checking for a function’s existence
<?php
if (function_exists("array_combine"))
{
    echo "Function exists";
}
else
{
    echo "Function does not exist - better write our own";
}
?>

Using code such as this, you can identify any features available in newer versions of PHP that you will need to replicate if you want your code to still run on earlier versions. Your functions may be slower than the built-in ones, but at least your code will be much more portable.

You can also use the phpversion function to determine which version of PHP your code is running on. The returned result will be similar to the following, depending on the version:

5.2.8

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.