MrChevin
MrChevin

Reputation: 3

if statement in foreach loop using last true value when false

I have an array being looped with an if-else statement in it. The condition is if the name starts with a dot put the string in $gridNames else put the string in $cssNames. Somehow the last name that was valid for $gridNames is being used for the rest of the loop although the condotion being false.

Here's the $selector["name"] array:

string(4) ".row"
string(10) ".inner_row"
string(7) ".column"
string(13) ".inner_column"
string(12) "hey im a div"
string(8) "column 1"
string(5) "row 2"

And the code itself:

foreach ($element_css["element_css"] as $selector) {
  $name = $selector["name"];
  $lenght = strlen($name);
  $firstLetter = substr($name, 0, -($lenght - 1));
  if ($firstLetter == ".") {
      $gridName = substr($name, 1, $lenght);
  } else {
      $nameByWords = explode(" ", $name);
      foreach ($nameByWords as $word) {
        $allWords .= $word;
      }
      $cssName = $allWords;
      $allWords = "";
  }
  var_dump($gridName);
}

The var_dump gives me:

string(3) "row"
string(9) "inner_row"
string(6) "column"
string(12) "inner_column"
string(12) "inner_column"
string(12) "inner_column"
string(12) "inner_column"

The result I want is:

string(3) "row"
string(9) "inner_row"
string(6) "column"
string(12) "inner_column"

Upvotes: 0

Views: 379

Answers (2)

Rahul Jain
Rahul Jain

Reputation: 357

var_dump($grid_name) will execute in every iteration of loop because this is written outside of if-else condition so for the last 3 strings, $grid_name wouldn't change but that var_dump() will execute so the last value of $grid_name would be used to display.

Upvotes: 1

John Sensebe
John Sensebe

Reputation: 1396

You never set $gridName to anything else, so what do you expect? You could set it to NULL or "" depending on what exactly you want, either at the beginning of the loop or inside the else clause. The latter is a little more efficient.

Upvotes: 0

Related Questions