PHP 8 – How to use ValueError to check if the value encountered is of correct type?

PHPServer Side ProgrammingProgramming

PHP 8 uses a new built-in exception ValueError. PHP throws this exception when we pass a value to a function, which has a valid type but cannot be used for operation. In the earlier versions of PHP, we used to get a Warning error in such cases, but PHP 8 will show a ValueError.

Example: ValueError in PHP 8

<?php
   declare(strict_types=1);
   array_rand([1,2,3], 0);
   json_decode('{}', true, -1);
?>

Output

Fatal error: Uncaught ValueError: array_rand(): Argument #1 ($array) cannot be empty

Example

 Live Demo

<?php
   $x = strpos("h", "hello", 16);
   var_dump($x);
?>

Output

bool(false)

Example: ValueError in PHP 8

<?php
   $x = strpos("h", "hello", 16);
   var_dump($x);
?>

Output

Fatal error: Uncaught ValueError: array_rand(): Argument #1 ($array) cannot be empty
raja
Published on 01-Apr-2021 06:51:19
Advertisements