I'm trying to add a new element to an array from form values in php. However every time I do this I overwrite the most recent element. So my existing array is like this:
$moviepages = [[ "title" => "test1",
"description" => "this is my test"
]
];
And I want to add this (created through form values) to it:
$newfile = [
"title" => "test2",
"description" => "test2",
];
by doing this:
$moviepages[] = $newfile;
However I need to add elements continuously so that when different users come in they can add items on to the same array without the previous array element getting removed. Is there a way to do this? Thanks!
If your form values are stored in an array you can try to use array_merge() to merge the two arrays together. For example;
array_merge($moviepages, $newFile)
EDIT
You can also try the array_merge_recursive() function as it does not delete the previous entries but just creates a new array for those values. For example;
This code;
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge_recursive($a1,$a2));
will produce this result;
Array ( [a] => red [b] => Array ( [0] => green [1] => yellow ) [c] => blue )
This explanation is from w3schools for the difference between the two.
The difference between this function(array_merge_recursive()) and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.
As for file_put_contents-, try to check out w3schools and tutorialspoint
Let me know if it works for you or if you have any problem.