Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda