How to add value to an array without losing the previous value?

Asked

Viewed 664 times

0

Through a form and a single input I need to receive multiple numbers and store these numbers in an array. For example, I type any number in the input and click on the form’s Submit button, with PHP I take this value and store it in the array. But if you do the same process again the previous value will be lost. How do I not lose it ? I tried to put input as text and pass all numbers at once, but I don’t know how to handle space and it’s not the focus using Regex. How can I do it without regex ?

  • Your question was a little vague. I suggest you put the code you said you tried and show which part was not working as you wanted.

  • I used the explode to take the values separated by space and transform into an array.

2 answers

1

The advisable would be to represent the variable as an array $array[] and including the values:

Simple:

$array[] = 'aaa';
print_r($array);
// resultado: Array ( [0] => aaa )

$array[] = 'bbb';
print_r($array);
// resultado: Array ( [0] => aaa [1] => bbb )

Using loop:

for ($x = 1; $x <= 10; $x++)
{
    $array[] = $x;
}
print_r($array);
// resultado: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 )

It also works, but not advisable because it is a function, so it becomes slower processing:

Simple:

$cesta = array("laranja", "morango");
array_push($cesta, "melancia", "batata");
print_r($cesta);

Loop:

for ($x = 1; $x <= 10; $x++)
{
    array_push($array, $x);
}

There are also several other methods, as an example, a little more used, the array_merge, that joins 2 or more arrays:

$result = array_merge($array1, $array2);

Documentations: array_push, array_merge


If you don’t answer your question, comment.

0

Since you didn’t post the code I’ll make an example

for($mes = 1; $mes <= 12; $mes++)
{
     $Val[] = $mes;
}

echo 'janeiro '.$Val[0];
echo 'março'.$Val[2];

That way the value will not overwrite, if you set a position within the repeater, it will always save in the same position.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.