note 47240 added to language.types.array
| From: | JoeMorrison | Date: | Mon, 08 Nov 2004 09:26:17 +0000 |
| Subject: | note 47240 added to language.types.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-80271@lists.php.net to get a copy of this message | ||
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))]);
}
?>
----
Manual Page -- http://www.php.net/manual/en/language.types.array.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+47240
Delete -- http://master.php.net/manage/user-notes.php?action=delete+47240&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+47240&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+47240&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+47240&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+47240&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+47240&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+47240&report=yes
Search -- http://master.php.net/manage/user-notes.php