dongliushui2001 2016-01-17 18:21
浏览 70
已采纳

if语句中的if语句在false时使用last true值

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"
  • 写回答

2条回答 默认 最新

  • dongzhashou0116 2016-01-17 18:32
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog