Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda