Search code examples
phpsessionforeachunset

Unsetting array value in foreach loop with session?


Can anyone please explain why the unset function do not work in the below code?

As I expected the $_SESSION['card_nr'] = $card_nr; stores the last looped $card_nr but I want it to store the card_nr the user click, thats why I need to unset (ps. I do not want to use GET).

I have tested different solutions based on web searches incl. stack overflow answers, but can not make the below work.

    $task_array = array_combine($task_id_unique, $task_status);
        foreach ($task_array as $card_nr => $card_status) { 
        $_SESSION['card_nr'] = $card_nr;
        ?>  
        <table>
          <tr>
            <th>Card nr.</th>       
            <th>Status</th>       
            </tr>
            <td><?php 
                            echo $card_nr;?></td>
            <td><?php 
                            if ($card_status == true) {
                            unset($task_array[$card_nr]);
                            echo "<a href=workcard.php>Open</a>";
                }
            else echo "Done ". $card_nr;?></td>
        </table>
<?php       }

Solution

  • I solved my question by doing the below:

    elseif (mysql_num_rows($results)>= 1) {
            echo "Customer: ". $customer. "<br>Active workcard:<br>";
            $task_array = array_combine($task_id_unique, $task_status);
                foreach ($task_array as $card_nr => $card_status) { 
                ?>  
                    <?php 
                    if ($card_status == true) { 
                        echo "<table><tr>";
                        echo "<th>Workcard nr.</th>";
                        echo "<th>Status</th></tr>";
                        echo "<td>".$card_nr."</td>";
                            echo "<td>";
                            echo "<form action='workcard_open.php' method='POST' >";
                            echo "<input type='hidden' name='card_nr' value='".$card_nr."' />";
                            echo "<input type='submit' value='Open' />";
                            echo "</td></form></table>";
                    }
                    ?>