0

I'm trying to display only the names that are not empty from this array on a new line for each. Currently, using this, it is only displaying "$playerName1"'s name 10 times. I'm trying to figure out why it's not actually looping through all 10 playerName's. It seems to only be checking $playerName1.

$z = array($playerName1, $playerName2, $playerName3, $playerName4, $playerName5, $playerName6, $playerName7, $playerName8, $playerName9, $playerName10);
$zCounter = 1;
foreach ($z as $allNames) {
  while ($allNames != "" && $zCounter < 11) {
    echo $allNames . "<br>";
    $zCounter++;
  }
}    
2
  • 1
    Get rid of the inner while loop. Commented May 31, 2013 at 18:51
  • On an issue unrelated to the question, but showing up in your code, consider using !empty($allNames). Commented May 31, 2013 at 18:56

3 Answers 3

4

Your problem is that you are going through the inner while loop for only the first player name. The outer foreach loop should be plenty:

foreach ($z as $playerName) {
  if ("" !== $playerName) {
    echo $playerName . "<br />";
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Unless you want to output each name 10 times, remove the while loop. You can still check to make sure the name is not empty by using !='' or empty()

<?php
$z = array($playerName1, $playerName2, $playerName3, $playerName4, $playerName5, $playerName6, $playerName7, $playerName8, $playerName9, $playerName10);
foreach($z as $name){
    if(!empty($name)){
        echo $name.'<br>';
    }
}

Comments

1

you need to reset the $zCounter after each while loop

foreach ($z as $allNames) {
  while ($allNames != "" && $zCounter < 11) {
    echo $allNames . "<br>";
    $zCounter++;
  }
  $zCounter = 0;
}  

otherwise after the first while loop finishes, $zCounter will always be 11

1 Comment

Why the downvote this perfectly fixes his problem. He didnt say anything about not wanting them each displayed 10 times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.