php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #79689 Casting a non-existent array index to int returns 0 instead of null
Submitted: 2020-06-11 15:44 UTC Modified: 2020-06-11 16:33 UTC
From: sebastian dot awatramani at gmail dot com Assigned:
Status: Not a bug Package: Unknown/Other Function
PHP Version: 7.4Git-2020-06-11 (Git) OS: Linux Mint 19
Private report: No CVE-ID: None
 [2020-06-11 15:44 UTC] sebastian dot awatramani at gmail dot com
Description:
------------
Using the null coalesce operator while casting a result to int, I expect that if the array index I'm trying to assign doesn't exist, it should fail and then move on to the next part of the NC statement, like so:

$a = (int) $_GET['field'] ?? null

If there is no $_GET['field'] nor a $_GET in general, I expect $a to equal null.  But instead $a ends up as 0 because casting a non-existent array index to int returns the int val of false

Test script:
---------------
$a = (int) $_GET['field'] ?? null

Expected result:
----------------
$a === null

Actual result:
--------------
$a === 0

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-06-11 15:56 UTC] bugreports at gmail dot com
please fix your expectations according how ternary operator works for many years now, your expected behavior would it make completly useless for 99% of all use cases
 [2020-06-11 16:00 UTC] nikic@php.net
-Status: Open +Status: Not a bug
 [2020-06-11 16:00 UTC] nikic@php.net
You are looking for;

    $a = (int) ($_GET['field'] ?? null);

Casts are high-precedence operators.
 [2020-06-11 16:00 UTC] brzuchal@php.net
Not a bug but expected behaviour.
 [2020-06-11 16:07 UTC] bugreports at gmail dot com
with proper error reporting you would seewhat really happens:
you are doing (int)$_GET['field'] which is afterward 0 and the ?? is a noop

php > $a = (int) $_GET['field'] ?? null; var_dump($a);
Notice: Undefined index: field in php shell code on line 1

> You are looking for
> $a = (int) ($_GET['field'] ?? null);

won't change anyhing, no way that is line ever results in expected result BULL, it will alway be int 0, one time with warnings and one time without beause in that version you cast the result of ($_GET['field'] ?? null) but you still cast

the only difference is if "?? null" is executed at all
 [2020-06-11 16:33 UTC] nikic@php.net
@bugreports: You are right. I skimmed this a bit too quickly. I believe what OP wants is just

    $a = isset($_GET['field']) ? (int) $_GET['field'] : null;

or

    $a = (?int) ($_GET['field'] ?? null);

with a hypothetical nullable cast operator (https://wiki.php.net/rfc/nullable-casting).
 
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Wed May 18 09:04:05 2022 UTC