Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP 8 – How to use ValueError to check if the value encountered is of correct type?
PHP 8 introduces a new built-in exception ValueError. PHP throws this exception when we pass a value to a function that has a valid type but cannot be used for the operation. In earlier versions of PHP, we used to get a Warning error in such cases, but PHP 8 will throw a ValueError instead.
What is ValueError?
ValueError is thrown when a function receives an argument of the correct type, but the value itself is inappropriate for the operation. This makes error handling more consistent and allows developers to catch these specific errors using try-catch blocks.
Example 1: array_rand() with Invalid Parameters
The array_rand() function throws ValueError when requesting 0 elements −
<?php
declare(strict_types=1);
try {
array_rand([1,2,3], 0);
} catch (ValueError $e) {
echo "ValueError: " . $e->getMessage();
}
?>
ValueError: array_rand(): Argument #2 ($num) must be between 1 and the number of elements in argument #1 ($array)
Example 2: strpos() with Invalid Offset
The strpos() function throws ValueError when offset is beyond string length −
<?php
try {
$x = strpos("hello", "h", 16);
var_dump($x);
} catch (ValueError $e) {
echo "ValueError: " . $e->getMessage();
}
?>
ValueError: strpos(): Argument #3 ($offset) must be contained in argument #1 ($haystack)
Comparison with PHP 7
| Function Call | PHP 7 Behavior | PHP 8 Behavior |
|---|---|---|
array_rand([1,2,3], 0) |
Warning + returns null | Throws ValueError |
json_decode('{}', true, -1) |
Warning + returns null | Throws ValueError |
Conclusion
ValueError in PHP 8 provides better error handling by throwing exceptions for invalid values instead of warnings. This allows developers to use try-catch blocks for more robust error handling and makes debugging easier.
