1

I'm struggling with clearing out an array when "clearYes" radio button is checked upon submit. It will appear to clear but as soon as I list the contents of the array everything is there again.

Here is the code

<?php
session_start();

// Initialize an array for answers
if (!isset($_SESSION['songArr']))
    $_SESSION['songArr'] = array();
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">

<head>
    <meta charset="utf-8">
</head>

<body>

    <form name="songform" action="" onsubmit=" return validateForm()" method="post">
        <table>
            <tr>
                <th>Song Name:</th>
                <th><input type="text" name="songName" size="20"></th>
            </tr>
            <tr>
                <th>Composer:</th>
                <th><input type="text" name="composer" size="20"></th>
            </tr>
            <tr>
                <th>Artist or Group:</th>
                <th><input type="text" name="artist" size="20"></th>
            </tr>
            <tr>
                <p><input name="radio1" type="radio" value="listSongs"> Show the list of songs? </p>
            </tr>
        </table>
        <p><input name="submit" type="submit" value="Submit Song" /> <input type="reset" value="Clear form" /></p>
        <p><input name="radio2" type="radio" value="clearNo" checked="checked"> Don't clear list. <input name="radio2" type="radio" value="clearYes">Clear list after submit.</p>
    </form>

</body>

<?php
if (!empty($_POST['submit'])) {
// Push the posted data into the session array
$_SESSION['songArr'][] = $_POST;
}
$listSongs= $_POST['radio1'];
// Display the data now
//if clearYes is selected
if ($listSongs == "listSongs") {
foreach($_SESSION['songArr'] as $array) {
    echo "<strong>Song name</strong>: {$array['songName']}<br>";
    echo "<strong>Composer</strong>: {$array['composer']}<br>";
    echo "<strong>Artists</strong>: {$array['artist']}<br><br>";
}
}
//if clearYes is selected
$resetArr= $_POST['radio1'];
if ($resetArr == "clearYes") {
unset($array);
$array = array();
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
}
?>

</html>
1
  • 1
    Try unset($_SESSION['songArr']); Commented Nov 8, 2016 at 18:49

1 Answer 1

1

You need to unset the source array :

Replace :

 unset($array);

With :

 unset($_SESSION['songArr']);

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.