php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #46576 Adding to end of array - strange behaviour
Submitted: 2008-11-14 17:56 UTC Modified: 2008-11-15 15:29 UTC
From: geo at vzemibg dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.6 OS: CentOS
Private report: No CVE-ID: None
 [2008-11-14 17:56 UTC] geo at vzemibg dot com
Description:
------------
I am submitting what in my view is uncorrect behaviour of the [] operator for arrays. It is a special case when the last element of the array is removed with unset() and then a new element is added using the arrname[] = xxxx syntax.

Reproduce code:
---------------
$teststring = "let's test this";
$testarr = explode(' ', $teststring);
print_r($testarr);echo "<br />";
unset($testarr[2]);
print_r($testarr);echo "<br />";
$testarr[] = 'new';
print_r($testarr);

Expected result:
----------------
Array ( [0] => let's [1] => test [2] => this )
Array ( [0] => let's [1] => test )
Array ( [0] => let's [1] => test [2] => new )

Actual result:
--------------
Array ( [0] => let's [1] => test [2] => this )
Array ( [0] => let's [1] => test )
Array ( [0] => let's [1] => test [3] => new )

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-11-15 15:29 UTC] lbarnaud@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

Try using $testarr = array_values($testarr) to remove the holes between the keys.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Dec 11 19:00:02 2025 UTC