note 47240 deleted from language.types.array by googleguy
| From: | googleguy@php.net | Date: | Sat, 12 Jan 2013 15:42:45 +0000 |
| Subject: | note 47240 deleted from language.types.array by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-192998@lists.php.net to get a copy of this message | ||
Note Submitter: Joe Morrison <jdm at powerframe dot com>
----
Programmers new to PHP may find the following surprising:
<?php
$x[1] = 'foo';
$x[0] = 'bar';
echo "Original array:\n";
var_dump($x);
array_pop($x);
echo "Array after popping last element:\n";
var_dump($x);
?>
The surprise is that element 0 is deleted, not element 1. Apparently the notion of "last
element" has more to do with how the array is stored internally than with which element has the
highest numeric index. I recently translated a Perl program to PHP and was bitten by this one.
My solution was to identify all the places in my code where I could prove that the array elements
were assigned sequentially. In those cases it is safe to use array_pop, array_splice, etc. since the
array indices correspond with the array layout. For the other cases, my solution was to write
replacements for the built-in array functions such as this one:
<?php
function safe_pop(&$a)
{
if (!isset($a))
return;
if (!is_array($a))
return;
if (count($a) == 0)
return;
unset($a[max(array_keys($a))]);
}
?>