I need to make a function which creates multidimensional array, with adjustable number of rows and columns, and generated random numbers of each row, also adjustable
I have this attempt now, but it seems to go into an infinite loop:
function make($length, $start, $end)
{
if ($length < abs($start - $end) 1)
{
for ($i = 0; $i < $length; $i )
{
while (!isset($array) || count($array) < $length)
{
$vel = rand($start, $end);
if (!isset($array) || !in_array($vel, $array))
{
$array[$i][] = $vel;
}
}
}
return $array;
}
else
{
return false;
}
}
Please help, I can`t seem to figure it out
I am calling it like the following:
$array5 = make(10, 15, 35);
The end result should look like the following (having the same number of rows as columns):
CodePudding user response:
You were not checking the right array parts in the loops
function make($length,$start,$end)
{
if ($length<abs($start-$end) 1){
for ($i=0; $i < $length; $i ){
while (!isset($array[$i]) || count($array[$i])<$length){
// ^^^^ ^^^^
$vel=rand($start,$end);
if (!isset($array[$i]) || !in_array($vel,$array[$i])){
// ^^^^ ^^^^
$array[$i][]=$vel;
}
}
}
return $array;
} else {
return false;
}
}
print_r( make(5,10,30) );
The RESULT
Array
(
[0] => Array
(
[0] => 30
[1] => 16
[2] => 27
[3] => 17
[4] => 26
)
[1] => Array
(
[0] => 21
[1] => 13
[2] => 19
[3] => 25
[4] => 12
)
[2] => Array
(
[0] => 12
[1] => 28
[2] => 20
[3] => 19
[4] => 27
)
[3] => Array
(
[0] => 23
[1] => 17
[2] => 12
[3] => 16
[4] => 15
)
[4] => Array (
[0] => 17
[1] => 11
[2] => 22
[3] => 13
[4] => 10
)
)