-1

I have defined the multidimensional array $binary:

$binary = [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]];

I want to create a function to display binary numbers from this array.

count($binary) should determine the amount of digits in the number, in this case 6.

My goal is for the function to display all possible variations of a (in this case six digit) binary number:

100000, 110000, 101000, 1001000 etc.

The only idea that I have is to create a series of foreach loops that are nested in each other:

foreach ($binary[0] as $digit) {
     foreach ($binary[1] as $digit) {
         etc.
     }
}

however the amount of arrays inside $binary might increase, as a result you'd have to adjust it manually which is not what I'm looking for.

Does anyone know how to program such a function?

  • 1
    The answer to the question you asked is, almost certainly, "*yes.*" But, on the assumption you want the people that *can* do this to show *you* how to do this, we need to know: how far did you get when you tried? What went wrong (and in what way)? What happened, or didn't happen? – David Thomas Oct 20 '18 at 16:40
  • You're on the right track with the foreach, but does each series have subseries of the same length? – Steven Linn Oct 20 '18 at 16:48
  • What you're looking for is the Cartesian product, there's an excellent implementation [here](https://stackoverflow.com/questions/6311779/finding-cartesian-product-with-php-associative-arrays#answer-15973172) and a [demo here](https://3v4l.org/N9BDC) – billyonecan Oct 20 '18 at 17:43

1 Answers1

0

I feel like something generic like this function would work well:

$length = 6;

function rangeToBase($_maxLength, $_start = 0, $_base = 2)
{
    $max = pow($_base, $_maxLength + 1) - 1;
    $range = range($_start, $max);

    if($_base != 10) {
        array_walk($range, function (&$item) use ($_base, $_maxLength) {
            $item =  str_pad( base_convert($item, 10, $_base), $_maxLength, '0', STR_PAD_LEFT );
        });
    }

    return $range;
}

echo implode(' ', rangeToBase($length));

Parameters are:

  • $_maxLength for the maximum length of your number.
  • $_start for the minimum number you want (0 in your case)
  • $_base for the converted base you need (2 in your case)

I use str_pad to display the zeroes in your string. The function returns an array of string which you can echo with implode().

Stefmachine
  • 382
  • 4
  • 11