2

I am trying to create a 2D array where $multiples[$i] = array(multiples of $i), $i = 1,2,3...

function getMultiples($factor, $start = 0, 10)
{
  $multiples = array();

  for($i = $factor + $start; $i < 10; $i+=$factor)
  $multiples[] = $i;

  return $multiples;
}

for($i = 2; $i < 10; $i++)
{
    $start = 0 ;

    $multiples[$i] = getMultiples($i, $start, 10);
}

However, when I var_dump

$multiples[2] = array(0 => 2)
$multiples[3] = array(0 => 3)
$multiples[4] = array(0 => 4)
...

Each element of $values has been intialized with only the first multiple in each array.

I've tested this with non-numerical key values and it works fine. Static key values also work. The dynamic key value $i seems to the problem, what is going on here?

bagel
  • 23
  • 5
  • I tried it and work well, each item in `$values` is array of three elements – Karim Harazin Oct 23 '16 at 08:46
  • Hmm you're right it does work... but this is a simplified version of my problem where it isn't working. So maybe the problem lies elsewhere! I'm going to dig around... – bagel Oct 23 '16 at 08:59

1 Answers1

0

If you want to get the multiples of a number, you need to update the getMultiples as following:

function getMultiples($factor, $start = 0, $max)
{
  $multiples = array();

  for($i = 2; $i < $max; $i++)
  $multiples[] = $i*$factor;

  return $multiples;
}

What we change?

  1. Loop 10 or $max time for($i = $factor + $start; $i < 10; $i+=$factor) to for($i = 2; $i < $max; $i++).
  2. Find multiple $multiples[] = $i; to $multiples[] = $i*$factor;
Karim Harazin
  • 1,463
  • 2
  • 16
  • 34
  • Both ways work but I think yours is neater - I'm over-complicating things as usual :) I found out the problem in my code - a few lines along I used `array_splice` instead of `array_slice` resulting in the truncated array! – bagel Oct 23 '16 at 11:20