PHP array_push in array within another array

Asked

Viewed 2,596 times

0

Good evening, I need to create a php code that meets the following situation:

I have an array of arrays $arrayTudo = [$array1, $array2, $array3];

I calculate an X value and want to play it in array1, for example. It could be in any one of them. How to do array_push in this case? You can play this X value in an array within another array?

Before coding I need to understand how to do this.

It would look something like this:

<%php
$array1 = [];
$array2 = [];
$array3 = [];

$arrayTudo = [$array1, $array2, $array3];

$x = 10;


array_push($arrayTudo[0], $x);
%>

select one of the arrays to receive the value X. The first array, for example. This is possible?

2 answers

0

Look for "matrix", sometimes it helps you...

It would be more - like this:

$array[0][0] = 10; 
$array[0][1] = 20;

Watch this video

In a repeat structure, you will need to know how to place each:

$a = 0;
while ($a < 3) {

   $b = 0;
   while ($b < 5) {

   $array[$a][$b] = $b*2;

   $b++;
   }

$a++;
}

echo '<pre>';
print_r($array);

Upshot:

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 2
            [2] => 4
            [3] => 6
            [4] => 8
        )

    [1] => Array
        (
            [0] => 0
            [1] => 2
            [2] => 4
            [3] => 6
            [4] => 8
        )

    [2] => Array
        (
            [0] => 0
            [1] => 2
            [2] => 4
            [3] => 6
            [4] => 8
        )

)

0


You can use a array_merge in this case. See:

$arrayTudo = [array1, array2, array3];

$x = 10;
$y = 20;

$arrayValores = [$arrayTudo[0] => [$x, $y]];

$result = array_merge($arrayTudo, $arrayValores);

The results:

var_dump($result[array1]);

Exit:

array (size=2)
  0 => int 10
  1 => int 20 

All:

 var_dump($result);

Exit:

array (size=4)
  0 => string 'array1' (length=6)
  1 => string 'array2' (length=6)
  2 => string 'array3' (length=6)
  'array1' => 
    array (size=2)
      0 => int 10
      1 => int 20 
  • I get it. I think that’s the logic I needed. I’ll test it. Thank you.

  • @Round dispose

Browser other questions tagged

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