简体   繁体   中英

removing session array variables from a foreach loop

im trying to wrote a code where i can remove variables from a session array

here is my code

index.php

    <?php
        if(isset($_POST['add']))
            {
            $_SESSION['temp'][]=$_POST['rfield'];   
            $_SESSION['scol_id'][]=$_POST['scol_id'];  

            }
       if(isset($_SESSION['temp']))
        {
            ?>
            <table width="100%" border="0" class = "table">
            <?php
            $x=0;
           foreach($_SESSION['temp'] as $temp)
            { 
                ?>
        <tr><td>
        <?php echo $temp; ?> 
        </td>
        <td><a href="removerf.php?id=<?php echo $x; ?>" rel="tooltip" title="remove" class="link"><i class="icon-remove"></i></a></td>
        </tr>
        <?php
            $x++;
            }
        ?>
        </table>
        <?php
        }
        ?>                          

removerf.php

    <?php
    session_start();

    unset($_SESSION['temp'][$_GET['id']]);

    header("location:reportmaker.php");

    ?>

the problem with my code is that sometimes it can delete variables and sometimes it dont

it also cant delete the first variable of the array for some strange reason

am i missing something?

thanks in advance

I wouldn't rely on $x being the correct array key. Could you try this instead?

<?php
if(isset($_POST['add']))
{
    $_SESSION['temp'][]=$_POST['rfield'];   
    $_SESSION['scol_id'][]=$_POST['scol_id'];  
}
if(isset($_SESSION['temp']))
{
    ?>
    <table width="100%" border="0" class = "table">
    <?php
    foreach($_SESSION['temp'] as $key => $temp)
    { 
    ?>
        <tr><td>
        <?php echo $temp; ?> 
        </td>
        <td><a href="removerf.php?id=<?php echo $key; ?>" rel="tooltip" title="remove" class="link"><i class="icon-remove"></i></a></td>
        </tr>
    <?php
    }
?>
</table>
<?php
}
?>  

Relying on $x to be the array key will lead to issues whenever you delete a key from the temp array. If your temp array is:

array(
    0 => 'foo',
    1 => 'bar'
)

and you delete 0 from the array, $x will still start off as 0, even though the array key 0 doesn't exist. ie you're making assumptions about the array keys that currently exist in your array.

In regards to foreach:

foreach($myArray as $arrayKey => $arrayValue){
     //$arrayKey is the array key of the element / index
     //$arrayValue is the actual element that is stored.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM