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


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

Updated on: 01-Apr-2021

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements