0

Here's my code:

$user = new User($_POST['login'], $_POST['password'], $_POST['mail'], $_POST['name']);
$users = json_decode(file_get_contents('users.json'));
$users[] = $user->toArray();
file_put_contents('users.json', json_encode($users));

When the json file is empty, user gets added correctly, but when a user already exists in json file, when I try to add another user using this code, it just replaces the existing user.

2
  • Do a print_r($users) please when there is something in $users Commented Nov 15, 2022 at 16:37
  • 1
    @RiggsFolly yeah, the problem is that "$users = json_decode(file_get_contents('users.json'));" equals NULL, but why? Commented Nov 15, 2022 at 16:42

1 Answer 1

2

Just needed to set 'associative' to true in json_decode:

$users = json_decode(file_get_contents('users.json'), true);
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.