Bug #72817 [Opn->Nab]: array null index silently casts to empty string

From: Date: Thu, 12 Jan 2017 11:04:21 +0000
Subject: Bug #72817 [Opn->Nab]: array null index silently casts to empty string
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-206552@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=72817&edit=1

 ID:                 72817
 Updated by:         peehaa@php.net
 Reported by:        php at abiusx dot com
 Summary:            array null index silently casts to empty string
-Status:             Open
+Status:             Not a bug
 Type:               Bug
 Package:            Variables related
 Operating System:   OS X 10.11
 PHP Version:        7.0.9
 Block user comment: N
 Private report:     N

 New Comment:

The docs actually mention this behavior so I am going to go with "not a bug".

http://php.net/manual/en/language.types.array.php

> Null will be cast to the empty string, i.e. the key null will actually be stored under
> "".

Not saying I particularly like it. 

If anything it should be a feature request.


Previous Comments:
------------------------------------------------------------------------
[2016-08-11 20:42:19] php at abiusx dot com

$a[false]=5 is equal to $a[0]=5
and
$a[true]=5 is equal to $a[1]=5

so why $a[null]=5 is $a[""]=5? Why do we even allow empty string indexes in an array!?

------------------------------------------------------------------------
[2016-08-11 20:39:19] php at abiusx dot com

Description:
------------
Accessing an array will a null index is equal to accessing it with an empty string index, which is
non-trivial and cause of many errors in applications.

When a developer writes 

$a[$index]=5;

They typically expect $index to be an index (regardless of type) and not null. But if it is null,
the command still works and is equal to:

$a[""]=5; //same as $a[null]=5;

There is no trivial reason why null should cast to empty string, rather than say 0 or any other
equivalent form. And this behavior typically should cause warnings or notices (although it breaks
BC).


Test script:
---------------
$a=[];
$a[]=4;
$a[null]=5;
$a[]=6;
var_dump($a);

Expected result:
----------------
E_NOTICE, E_WARNING or $a[0]=5, but not $a[""]=5


Actual result:
--------------
array(4) {
  [0]=>
  int(4)
  [""]=>
  int(5)
  [1]=>
  int(6)
  [2]=>
  int(7)
}


------------------------------------------------------------------------



--
Edit this bug report at https://bugs.php.net/bug.php?id=72817&edit=1


Thread (3 messages)

« previous php.bugs (#206552) next »