Cain Nuke
Cain Nuke

Reputation: 3103

PHP while loop is giving me a random number of results

this code below is supposed to pick 5 random members from a text file and display them one after the other:

function display() {
 $open_file = fopen("members.txt", 'r');
 $members = explode("*", fgets($open_file));
 $members_num = count($members);
 $i=1;
 shuffle($members);
 while($i <= 5) {
   $details = explode("|", $members[$i++]);
   if(!empty($details[0])) {
   echo <<<EOF
    $details[0] $details[1] $details[2] 
EOF;
}
 }
  fclose($open_file);
}

ob_start();
display();
$display = ob_get_contents();
ob_end_clean();

$content=<<<EOF
 some text here $display more text
 <br>
 etc.
EOF;

echo $content;

This is the content of members.txt:

*James Johnson|USA|Male|1*Mary Reis|Germany|Female|2*Lin Xi|China|Male|3*Jessica Andrew|UK|Female|4*

The problem is that it wont always display 5, from time to time it displays only 4 and some other times 6. Why is that? How can I fix it so it displays only 5 ALWAYS?

Thank you.

Upvotes: 1

Views: 66

Answers (1)

Barmar
Barmar

Reputation: 781721

Since you have * at the end of the line, one of the elements of $members will be an empty string. When you get to that element, explode('|', $members[$i++]) will return the array [''], so if(!empty($details[0])) will skip it. But since you incremented $i, that causes you to display only 4 members.

I can't see any way that your code could display 6 members, though.

The fix is to only use * between elements, not after them. Or remove the empty string from $members.

$members = array_filter($members);

Upvotes: 1

Related Questions