Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Add element to array without overwriting it in php?

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!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!