Forum Moderators: coopster

Message Too Old, No Replies

unset array item within a loop problem

         

carsten888

9:51 am on Dec 9, 2007 (gmt 0)

10+ Year Member




<?php
//if component is not selected, take it out of array
for($n = 0; $n < count($components); $n++){
if(!isset($components[$n][active])){
unset ($components[$n]);
//$components[$n][name] = $components[$n][name].'NOT_THIS_ONE';
}
}

print_r($components);exit;
?>

I'm trying to take out the array-item that does not have a key (and value) "active".!
unset seems to behave realy wierd. I can't put my finger on where it goes wrong.
if I take the 'unset' away, and uncomment the line underneath, it does select the right array-items, so I'm pretty sure my selector (isset($compo... etc.) works fine. it outputs:

Array ( [0] => Array ( [active] => 1 [name] => pages and items [link] => com_pi_pages_and_items [order] => 1 ) [1] => Array ( [name] => contact formulierNOT_THIS_ONE [link] => com_form [order] => 2 )

How to take those items out of the array?

carsten888

3:59 pm on Dec 9, 2007 (gmt 0)

10+ Year Member



update:

I think the problem is that with unset() a sub-array gets deleted, the next array gets the index-number from the deleted sub-array. in the next loop the script checks the next array, so basically does not check the array that replaced the deleted one.

I'm trying to check if this is what is actually happening. But even if it is, it is not easy to fix.

I tried:
$rows = count($components);
for($n = 0; $n < $rows; $n++){
if(!isset($components[$n][active])){
unset ($components[$n]);
//$components[$n][name] = $components[$n][name].'NOT_Active';
$n = $n - 1;
}
}

but this spins my localhost into a loop.

gergoe

1:46 am on Dec 10, 2007 (gmt 0)

10+ Year Member



Your last one might have been working, but you forgot to update the $rows variable with the decremented item count, and additionally, removing array items, does not change the keys of the array, the removed key will stay unsused. So for example issuing the unset($array[1]) command on the array(0=>'0', 1=>'1', 2=>'2') array, will result in this one: array(0=>'0', 2=>'2'). So the length of the array changes, but the keys not. I'd suggest to implement this in a while loop with the each() iterator:


while (list($key, $val) = each($components)) if (!isset($val['active'])) unset($components[$key]);

carsten888

7:16 am on Dec 10, 2007 (gmt 0)

10+ Year Member



good point.

last night I managed it with this code:

$rows = count($components);
for($n = 0; $n < $rows; $n++){
if(!isset($components['d'.$n][active])){
unset ($components['d'.$n]);
}
}

I read on php.net 1 line in a post that there is a problem with these things if key is an integer, so I added a letter and all was fine.

thanks for the help.