user3504199
user3504199

Reputation: 71

How to add element to array without rewriting previous? - PHP

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?

Upvotes: 1

Views: 106

Answers (1)

Timr
Timr

Reputation: 1032

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.

Upvotes: 1

Related Questions