Array inside array ... using array_push

0

For purposes of study and better understanding I'm trying to make an array inside another array by adding values using array_push, 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: \ StudyPHP \ arrays.php on line 12 Array1234

As per error, I do not understand the correct logic for this.

    
asked by anonymous 22.09.2014 / 20:42

2 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";

Output:

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',
  ),
)
    
22.09.2014 / 20:49
0

I think you should be trying something along these lines:

$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 . ', ';
  }
}
    
23.09.2014 / 13:58