Forum Moderators: coopster

Message Too Old, No Replies

Missing array key after unsetting another key

Maybe I don't understand this as well as I thought

         

Artie_J

1:52 pm on Apr 5, 2006 (gmt 0)

10+ Year Member



Alrighty code gurus!
I've boiled this down to a simple example.
There are two array, $dropa and $itema. I have a loop that unsets an $itema key if the corresponding $dropa position has a value (Drop).
The loop gets rid of the key OK, but then when I reference a key that should be there according to the print_r(array_values()) command, it's not there! Copy and run this to see what I mean:

<?php
$drop1="Drop";
$item0="Zero";
$item1="One";
$item2="Two";

$dropa = array($drop0,$drop1,$drop2);
$itema = array($item0,$item1,$item2);

print "<br>itema array: ";
print_r(array_values($itema));
print "<br>";

$dr=0;
while($dr < 3){
if($dropa[$dr]=="Drop"){
unset($itema[$dr]);
}
$dr++;
}

print "<br>itema array after unset: ";
print_r(array_values($itema));
print "<br>";
print "itema[0]: ".$itema[0]."<br>";
print "itema[1]: ".$itema[1]."<br>";

?>

The output in my browser is:
itema array: Array ( [0] => Zero [1] => One [2] => Two )

itema array after unset: Array ( [0] => Zero [1] => Two )
itema[0]: Zero
itema[1]:

HAH?
Wha hoppened to $itema[1]?

coopster

2:47 pm on Apr 5, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You just have a misunderstanding of how arrays work. If you unset [php.net] an array index, you remove that key/value pair from the array. If you want the key to remain, just initialize it's value instead.


Arrays [php.net]
To change a certain value, just assign a new value to an element specified with its key. If you want to remove a key/value pair, you need to unset() it.

Artie_J

3:36 pm on Apr 5, 2006 (gmt 0)

10+ Year Member



Oh...
So the [1] in the array_values output is not key 1 of the original $itema array. array_values just puts out it's own array where there are values.

I'm glad to provide these gleaming examples of what not to assume in PHP programming at no charge to this community. :-)

coopster

10:24 pm on Apr 5, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



hehe, well arrays can be a different animal altogether. Some functions renumber numeric keys, some don't. If you need the array to maintain the indices in any certain fashion it is best to remember to test test test. I often find myself going back to the manual quite often when working with arrays. That, and I've made myself quite the array snippet collection to refresh my memory ;)