php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #49824 Change array_fill() to allow creating empty array
Submitted: 2009-10-09 17:09 UTC Modified: 2013-11-12 21:10 UTC
Votes:5
Avg. Score:3.8 ± 0.7
Reproduced:5 of 5 (100.0%)
Same Version:2 (40.0%)
Same OS:2 (40.0%)
From: soapergem at gmail dot com Assigned: nikic (profile)
Status: Closed Package: Arrays related
PHP Version: * OS: *
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: soapergem at gmail dot com
New email:
PHP Version: OS:

 

 [2009-10-09 17:09 UTC] soapergem at gmail dot com
Description:
------------
Right now array_fill() returns false and throws an E_WARNING if its second parameter ($num) is less than 1. This is counter-intuitive. As you know, the purpose of array_fill is to create an array with the given number of elements, all preset to one value. The restriction SHOULD be that $num cannot be less than 0, rather than saying it cannot be less than 1.

Why? Because an array of zero-length is a perfectly valid thing in PHP. I ran into a scenario where I was using array fill and $num was a dynamic value. I would have never expected that PHP would actually throw a warning if I told it to create an empty array. I had to write a wrapper function to accommodate, which is stupid. Just allow me to create an empty array like any reasonable person would expect!

Reproduce code:
---------------
<?php

$array1 = array_fill(0, -1, 1);
$array2 = array_fill(0, 0, 1);
$array3 = array_fill(0, 1, 1);

var_dump($array1);
var_dump($array2);
var_dump($array3);

?>

Expected result:
----------------
bool(false)
array(0) {
}
array(1) {
  [0]=>
  int(1)
}
PHP Warning:  array_fill(): Number of elements must be nonnegative in C:\test.php on line 3


Actual result:
--------------
bool(false)
bool(false)
array(1) {
  [0]=>
  int(1)
}
PHP Warning:  array_fill(): Number of elements must be positive in C:\test.php on line 3
PHP Warning:  array_fill(): Number of elements must be positive in C:\test.php on line 4


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-12-14 16:39 UTC] jani@php.net
-Summary: Change the behavior of array_fill ever so slightly +Summary: Change array_fill() to allow creating empty array -Package: Feature/Change Request +Package: Arrays related -Operating System: WinXP +Operating System: * -PHP Version: 5.3.0 +PHP Version: *
 [2013-11-12 21:10 UTC] nikic@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: nikic
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue Dec 03 17:01:29 2024 UTC