Voting

: eight minus zero?
(Example: nine)

The Note You're Voting On

Julien T.
4 months ago
Building upon Allan R.'s initial idea, I've developed an improved version of the json_validate function for those using PHP 8.2 and earlier versions. This function emulates the functionality introduced in PHP 8.3, providing an effective way to validate JSON strings in earlier PHP versions.

```php
if (!function_exists('json_validate')) {
/**
* Validates a JSON string.
*
* @param string $json The JSON string to validate.
* @param int $depth Maximum depth. Must be greater than zero.
* @param int $flags Bitmask of JSON decode options.
* @return bool Returns true if the string is a valid JSON, otherwise false.
*/
function json_validate($json, $depth = 512, $flags = 0) {
if (!is_string($json)) {
return false;
}

try {
json_decode($json, false, $depth, $flags | JSON_THROW_ON_ERROR);
return true;
} catch (\JsonException $e) {
return false;
}
}
}
```

Key Improvements:

- String Check: Added a validation to ensure the input is a string.
- Error Handling: Utilizes try-catch to effectively catch and handle JsonException.
- Backward Compatibility: Safely integrable in older PHP versions, automatically deferring to native functionality in PHP 8.3+.

<< Back to user notes page

To Top