Jump to content

for() problem - should show all results


firedealer

Recommended Posts

Below the PHP code will show the first record only. If I replace $chunks in for() to the true number which is 5, it will show two records.  I need $chunks to be there for customize from $_POST.  Any solution?  Thanks.

 

<?php
// Retrieve from $_POST which isn't included in this code for now.
$word = "applesauce";
$number = 5;

$chunks = ceil(strlen($word)/$number);

echo "The $number-letter chunks of '$word' are:<br />\n";
for ($i=0; $i < $chunks; $i++) {
$chunks = substr($word, $i*$number, $number);
printf("%d: %s<br />\n", $i+1, $chunks);
}
?>

Link to comment
https://forums.phpfreaks.com/topic/204995-for-problem-should-show-all-results/
Share on other sites

Yes, my head was somewhere else.

 

You're reassigning $chunks within the loop.

 

$word = "applesauce";
$number = 5;

$chunks = ceil(strlen($word)/$number);

echo "The {$number}-letter {$chunks} of '{$word}' are:<br />\n";
for ($i=0; $i < $chunks; $i++) {
$chunks2 = substr($word, $i*$number, $number);
printf("%d: %s<br />\n", $i+1, $chunks2);
}

Thanks for a solution code.  Here mine is:

<?php
$word = "applesauce";
$number = 5;
$calc = ceil(strlen($word)/$number);
$howmany = $calc;
$chunks = $calc;

echo "The $number-letter chunks of '$word' are:<br />\n";
for ($i=0; $i < $howmany; $i++) {
$chunks = substr($word, $i*$number, $number);
printf("%d: %s<br />\n", $i+1, $chunks);
}

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.