php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #78513 compact('0') (any int) will generate an array with inaccessible key
Submitted: 2019-09-08 18:51 UTC Modified: 2021-07-19 13:16 UTC
Votes:2
Avg. Score:4.5 ± 0.5
Reproduced:2 of 2 (100.0%)
Same Version:1 (50.0%)
Same OS:1 (50.0%)
From: tandre@php.net Assigned:
Status: Open Package: Arrays related
PHP Version: Irrelevant OS: Linux/Any
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: tandre@php.net
New email:
PHP Version: OS:

 

 [2019-09-08 18:51 UTC] tandre@php.net
Description:
------------
compact('0') (or any other number) will generate an array with inaccessible keys if a variable with that value is defined.

I can't think of any reason to actually do this in real code, but I'd also expect all functions to return arrays with accessible keys.

Note that ext/opcache/Optimizer/zend_func_info.c may need to be changed depending on how this is fixed, to add MAY_BE_ARRAY_KEY_LONG.

    F1("compact",                      MAY_BE_NULL | MAY_BE_ARRAY | MAY_BE_ARRAY_KEY_STRING | MAY_BE_ARRAY_OF_REF | MAY_BE_ARRAY_OF_ANY),

I'd suggest limiting the fix to development php versions(php 7.4/8.0).

https://bugs.php.net/bug.php?id=61655 was a similar issue with inaccessible array keys, but had a different cause (casting object to array)

Test script:
---------------
<?php
call_user_func(function () {
    ${0} = 'value';
    $result = compact('0');
    var_export($result);
    var_export($result[0]);
});


Expected result:
----------------
Should emit the following output, with an integer array key (0, not '0') that can be accessed.

array(
  0 => 'value'
)'value'

Alternatively, it could throw/return an error value.

Actual result:
--------------
php test.php
array (
  '0' => 'value',
)Notice: Undefined offset: 0 in /home/tyson/test.php on line 6
NULL

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2019-09-09 07:58 UTC] nikic@php.net
There's a larger underlying issue here:

${0} = 'value';
var_dump($GLOBALS[0]); // Notice: Undefined offset: 0

Only works on HHVM an PHP < 5.0.

Same for the other way around:

$GLOBALS[0] = 'value';
var_dump(${0}); // Notice: Undefined variable: 0
 [2021-07-19 13:16 UTC] cmb@php.net
Also, the fix would introduce a BC break: <https://3v4l.org/CnQhfT>.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Dec 30 14:01:28 2024 UTC