Jump to content

Loop problem, for and while.


Degen

Recommended Posts

Hi!

 

I have a code that don't do want I want that to do.

<?php

$chars = str_split('abc');

$char_len = count($chars);

$length = 3;

 

//loop for char_len^length   

$loop_length = pow($char_len, $length);

for($i = 0; $i < $loop_length; $i++) {

 

  //convert $a to chars

  $string = '';

  while($a != 0) {

    $string = $chars[$a  % $char_len] . $string;

    $a = (int) ($a / $char_len);

  }

  //pad and print string

  echo str_pad($string, $length, $chars[0], STR_PAD_LEFT), "<br>\n";

  if($loop_length-1 == $i){

$length++;

}

  }

?>

 

And what it do, is to print out all combination of a, b and c. My problem is that when the loop is done (you'll se my if statement) I want to add one on length so it print out a, b and c in four letters. ex abca, abcb. But it isen't working.

 

Have you any clue that can help me? Thank you for your answer.

Link to comment
https://forums.phpfreaks.com/topic/236155-loop-problem-for-and-while/
Share on other sites

Well, you don't actually increase the $loop_length in your if statement, so the loop will just end again. You'd need to reset the $loop_length, but also take note that this will make the loop go on for ever, well for a while anyway. So make sure you add in something to stop the loop at some stage. A simple boolean check somewhere to break out of the loop or something to that effect.

Okey, but I don't want to add one in my $loop_length but one in $length and then run $loop_length again but with one bigger nummer then before. Do you understand what I'm after?

And I know I haven't got an ending get but as soon this loop will work I will set a stop on it, but thank you for telling me how I can do it.

Not really,

 

In this calculation their is 3 letters and I want it to be 3 letters long, so it is 3^3.

When that loop is done, I want to add one in how long the "word" will be, 4 in this case. So the math will be 3^4 many words.

And when that is done, add one more to the length of the "word" so it will be 5 and be math is now 3^5 many words.

Then it countine in the same procsess.

Was I clear enuff?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.