Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Jul 2003
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

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

    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

  • #2
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    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).

  • #3
    New to the CF scene
    Join Date
    Jul 2003
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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>";

    ?>

  • #4
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    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.

  • #5
    New to the CF scene
    Join Date
    Jul 2003
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •