How can PHP developers ensure compatibility with different PHP versions when writing scripts?

To ensure compatibility with different PHP versions when writing scripts, PHP developers can use version checking functions to determine the PHP version running on the server and adjust their code accordingly. By checking the PHP version before executing certain functions or features, developers can prevent compatibility issues and ensure their scripts run smoothly across different PHP versions.

// Check PHP version before executing code
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
    // Code compatible with PHP 7 and above
    // Add your PHP 7 code here
} else {
    // Code for PHP versions below 7
    // Add your PHP 5 code here
}