Search code examples
php-7null-coalescing-operator

How can I use 'null coalescing operator' together with converting values if they exists?


This is my code

$bookid = (int)$_POST['bookid'] ?? 0;
$userid = (int)$_POST['userid'] ?? 0;
$binding = (int)$_POST['binding'] ?? 0;
$colorpages = (int)$_POST['colorpages'] ?? 0;

and I am getting an error: Undefined index: binding in ... I know I am getting this error because I am using (int) function to a null variable, but how can i fix this? Convert the value to int and still be able to use the coalescing operator if there is not any value. Thanks!


Solution

  • $bookid = (int)($_POST['bookid'] ?? 0);
    $userid = (int)($_POST['userid'] ?? 0);
    $binding = (int)($_POST['binding'] ?? 0);
    $colorpages = (int)($_POST['colorpages'] ?? 0);
    

    So (int) won't have to deal with the null values