user1646859
user1646859

Reputation:

Getting specific numbers in for loop

I want to get 3 int values in a for loop connected with each other. What I basically want is this:

000
001
002
003
010
011
...
323
330
331

I want to have each of the 3 numbers in a variable starting from 0 and max 3 when it gets higher than 3 it increases the number left to it by 1

For example

for($i = 0; $i <= $array; $i++){
 echo $a . $b . $c . "<br />"; //Output would be the example I showed above
}

Upvotes: 0

Views: 547

Answers (4)

Dan
Dan

Reputation: 10786

for($i = 0; $i <= 63; $i++){
 $c = $i % 4;
 $b = ($i - $c)/4 % 4;
 $a = (($i - $c)/4 - $b)/4;
 echo $a . $b . $c . "<br />"; //Output would be the example I showed above
}

It's really just an explicit version of knittl's answer. The for loop has us step through every number from 0 thru 63, which happens to correspond with 0 through 333 in base 4. We then take $i, which is in base 10, and convert it to base 4 step by step. The % is the modulo operator - it returns the remainder after division. The least significant char is simply the remainder of $i/4, so we save that as $c. The next char is the 4 place (like the 10 place in base 10). So we subtract $c, which is already accounted for and divide by 4 and do the same thing.

Upvotes: 1

knittl
knittl

Reputation: 265161

You can use base_convert to convert between arbitrary bases, in your case base 4.

for($i=0, $max = base_convert(333, 4, 10); $i < $max; ++$i) {
  echo base_convert($i, 10 , 4);
}

To get 0-padded output, use printf with a format specifier:

printf('%03d', base_convert($i, 10 , 4));

Upvotes: 4

Jakub Matczak
Jakub Matczak

Reputation: 15656

Try this:

$count = 20; //how many numbers do you want
for($i =0; $i<$count; $i++) {
    echo str_pad(base_convert($i, 10, 4),3,'0' , STR_PAD_LEFT) . '<br/>';
}

base_convert() converts every $i value from 10 base to 4.

str_pad() fill it with '0' to given length (3 here).

STR_PAD_LEFT means that zeros should be added on left side.

Upvotes: 1

Hilmi
Hilmi

Reputation: 3439

for($a = 0; $a <= 3; $a++){
 for($b = 0; $b <= 3; $b++){
    for($c = 0; $c <= 3; $c++){
       echo $a . $b . $c . "<br />";
     }
  }
}

Upvotes: 1

Related Questions