1

I'm trying to add elements to an array after typing their name, but for some reason when I do

<?php
    session_start();
    $u = array("billy\n", "tyson\n", "sanders\n");
    serialize($u);
    file_put_contents('pass.txt', $u);

    if (isset($_POST['set'])) {
        unserialize($u);
        array_push($u, $_POST['check']);
        file_put_contents('pass.txt', $u);
    }
?>

<form action="index.php" method="post">
    <input type="text" name="check"/><br>
    <input type="submit" name="set" value="Add person"/><br>
    <?php echo print_r($u); ?>
</form>

It puts it in the array, but when I do it again, it rewrites the previous written element. Does someone know how to fix this?

8
  • What do you mean after typing their name? Commented Apr 26, 2014 at 3:39
  • I was referring to my entire script, it's about typing your name, and it being added to the array and so on, I just didn't want to show it all. Commented Apr 26, 2014 at 3:42
  • 1
    Then show an example where this issue can be reproduced. It works fine for me. Commented Apr 26, 2014 at 3:43
  • @user3504199 can you show the form etc? Commented Apr 26, 2014 at 3:44
  • You can't keep arrays from different form submits, to do that you will need to use $_SESSION['person'][] = $u; Commented Apr 26, 2014 at 3:55

1 Answer 1

1

You always start with the same array, which means no matter what you do you're going to only be able to add one person. I /think/ you're trying to add each person to the file, which can be accomplished by modifying the code to resemble something like this:

session_start();

$contents = file_get_contents('pass.txt');    

if (isset($_POST['set'])) {
    $u = unserialize($contents);
    array_push($u, $_POST['check'] . "\n");
    $u = serialize($u);
    file_put_contents('pass.txt', $u);
}

Notice also that you can't use [un]serialize() on its own, it must be used in the setting of a variable.

**Note: Personally, I'd just go the easy route and do $u[] = $_POST['check'], as using array_push() to push one element seems a bit... overkill.

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

1 Comment

But what if I wanted to add an element to the array aswell?

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.