Array inside array... using push arrays

Asked

Viewed 21,786 times

1

For study purposes and better understanding I am trying to make an array within another array by adding values using the push array_follow my example:

<?php

$ar1 = array();
array_push($ar1, 1, 2, 3, 4);

foreach($ar1 as $ar) {
    $ar2 = array();
    array_push($ar2, 5, 6, 7, 8);
    array_push($ar1, $ar2);

    foreach($ar1 as $ar) {
        echo $ar . "";
    }
}

Notice: Array to string Conversion in D: Estudophp arrays.php on line 12 Array1234

As far as I’m concerned, I don’t understand the correct logic for this.

  • 2

    echo $ar . ""; is to mix array with string..., do var_dump($ar); instead of this echo

3 answers

1

I think what you’re looking for is something like this:

$first = array('doh', 'ray', 'me');
$second = array('fah', 'soh', 'lah', 'te', 'do');

echo "Union: ", var_export($first + $second, true), "\n";
echo "Merge: ", var_export(array_merge($first, $second), true), "\n";

// array_push returns int, not an array:
array_push($first, $second);
echo "Push: ", var_export($first, true), "\n";

Exit:

Union: array (
  0 => 'doh',
  1 => 'ray',
  2 => 'me',
  3 => 'te',
  4 => 'do',
)
Merge: array (
  0 => 'doh',
  1 => 'ray',
  2 => 'me',
  3 => 'fah',
  4 => 'soh',
  5 => 'lah',
  6 => 'te',
  7 => 'do',
)
Push: array (
  0 => 'doh',
  1 => 'ray',
  2 => 'me',
  3 => 
  array (
    0 => 'fah',
    1 => 'soh',
    2 => 'lah',
    3 => 'te',
    4 => 'do',
  ),
)
  • Wow, just use the merge array_merge then, interesting. I will analyze this well, thanks. But it is because I also wanted to assemble an array.

0

I believe you must be trying something in this sense:

$ar1 = array(1 => array(), 2 => array(), 3 => array(), 4 => array());

$size = count($ar1);
/** Adiciona um array novo com os valores 5, 6,7 e 8 a cada posicao do array $ar1*/
for ($i = 0; $i < $size; $i++) {
    $ar1[$i] = array(5, 6, 7, 8);
}

foreach ($ar1 as $chave => $valor) {
  echo 'Mostrando array ' . $chave . '<br />';
  foreach ($valor as $valor2) {
    echo $valor . ', ';
  }
}

0

Thus: //Array to generate new indices $pos1=[1,2,3,4,5,6,7,8,9,10];

//Function [array_fill] $pos=array_fill(0,10,$pos1);

Exit: array (size=10) 0 => array (size=10) 0 => int 1 1 => int 2 2 => int 3 3 => int 4 4 => int 5 5 => int 6 6 => int 7 7 => int 8 8 => int 9 9 => int 10 1 => array (size=10) 0 => int 1 1 => int 2 2 => int 3 3 => int 4 4 => int 5 5 => int 6 6 => int 7 7 => int 8 8 => int 9 9 => int 10 2 => ..........

Browser other questions tagged

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