...

View Full Version : i am trying to use the unset() function..but it's doesnt work..



melnet
07-11-2007, 06:37 PM
Hello

i am trying to use the unset() function..but it's doesnt work..

code here:
$str=array();

$num1=1;
$num2=2;
$num3=1;

$id="a";

$str[$id]=$num1;
$id="b";
$str[$id]=$num2;
$id="c";
$str[$id]=$num3;

foreach ($str as $key=>$value){
if ($value==1)
unset($str[$id]);
echo "$key - $value <br>";
}
?>

i want to do checking all values equal 1 then delete all related var names
for examle a=1 so delete it
but dont know why it doesn't work...
where do i code wrong sth?

Thanks

Fumigator
07-11-2007, 06:58 PM
Your code is really close but you need to use the $key variable as the index to do the unset() rather than the $id variable (which is equal to 'c' the entire duration of the foreach loop).

melnet
07-11-2007, 07:30 PM
Thanks for your helpful
i recode again, like this code?
and i never learn c lang.
so i dont know the foreach will loop forever.
any problem to fix it?
<?
$str=array();
$new_num=10;
$num1=1;

$id="a";

$str[$id]=$num1;
$id="b";
$num1=1;
$str[$id]=$num1;
$id="c";
$num1=2;
$str[$id]=$num1;

foreach ($str as $id){
if ($str[$id]==2)
$str[$id]=$new_num;
}

foreach ($str as $id=>$num1)
echo "$id - $num1 <br>";

?>

Fumigator
07-11-2007, 07:40 PM
and i never learn c lang.
so i dont know the foreach will loop forever.

Foreach loops don't loop forever; what gave you that idea?

You are no longer using unset() but if your code does what you need it to do then problem solved.

melnet
07-11-2007, 07:51 PM
hum...
now i can't delete it and edit it
but if ($str[$id]==2) , this code works
i dont know why the key still exist..

any suggestion to do so?

Thanks fo help



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum