D
D
dimka_shaman2018-03-28 14:26:18
PHP
dimka_shaman, 2018-03-28 14:26:18

I don't understand why I am getting this output?

I'm learning PHP and I've come across an incomprehensible output.
I wrote a code that is supposed to create an array of 10 arrays of 10 random digits from 1 to 10 each...

<?php

    $arr = array_fill(0,10,[]);   //создаю массив массивов
    foreach ($arr as $element) {

                 for ($i=0;$i<10;$i++) $element[] = rand(1,10);    //забиваю рандомные цифры в подмассив
                 var_dump($element); echo '<br>';  //проверяю получившийся подмассив
    }
        echo '<br>';
    var_dump($arr);  //проверяю массив, вардамп показывает что у меня массив из 10 пустых подмассивов... ???
    echo '<br>'.'<br>';
    var_dump($arr[3]);  //проверяю 4 подмассив и показывает пустой массив..
    
    ?>

It looks like $arr doesn't get changed by the loop, but should it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav B, 2018-03-28
@dimka_shaman

some documentation
In order to directly change the elements of an array within a loop, the $value variable must be preceded by an & sign. In this case, the value will be assigned by reference. (c)

S
Sanovskiy, 2018-03-28
@Sanovskiy

The easiest option

<?php
$arr = [];
for ($ii=0;$ii<10;$ii++){
  $arr[$ii] = [];
  for ($jj=0;$jj<10;$jj++){
    $arr[$ii][$jj] = rand(1,10);
  }
}
var_dump($arr);

But the code is a little more interesting
<?php

$arr = array_fill(0,10,null);

$arr = array_map(function($elem){
  $elem = array_fill(0,10,null);
  return array_map(function($subelem){
    return rand(1,10);
  },$elem);
},$arr);

var_dump($arr);

array_map()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question