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

0

Through a form and a single input I need to receive multiple numbers and store those numbers in an array. Example, I type any number in the input and click on the submit button of the form, with PHP I get 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 putting the input as text and pass all the numbers at once but I do not know how to deal with the space and it is not the focus to use Regex. How can I do this without regex?

    
asked by anonymous 21.04.2018 / 19:29

2 answers

0

As you have not posted the code I will make an example

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

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

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

    
23.04.2018 / 16:19
0

The advisable would be to represent the variable as array $array[] and including 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);

With loop:

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

There are also several other methods, for example, a little more used, the array_merge , which joins 2 or more arrays:

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

Documentation: array_push , array_merge

If you do not answer your question, please comment.

    
23.04.2018 / 18:20