Answer the question
In order to leave comments, you need to log in
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 подмассив и показывает пустой массив..
?>
Answer the question
In order to leave comments, you need to log in
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)
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);
<?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);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question