dpl74687
dpl74687
2017-08-25 15:15

php for循环为字符串值创建未定义的变量[重复]

已采纳

I am looping though my data and strong the result in a variable. It is currently being stored as strings.

for ($i = 0; $i < count($AnotherArray); $i++){

  $myArray  .= $dataArray[$i].",";
 }

This correctly returns the content with commas separating the values. But i get a notice

Notice: undefind variable: $myArray in ...

The above is the first time i create and call $myArray

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongzhimeng2464 dongzhimeng2464 4年前

    You need to have the variable defined before you can append to it

    $myArray="";
    for ($i = 0; $i < count($AnotherArray); $i++){
    
      $myArray  .= $dataArray[$i].",";
     }
    
    点赞 评论 复制链接分享
  • doujiao7679 doujiao7679 4年前

    You need to declare the $myArray variable first. So your code becomes:

    $myArray = '';
    for ($i = 0; $i < count($AnotherArray); $i++){
        $myArray .= $dataArray[$i].",";
    }
    

    As a side note, I'd also recommend looking at the naming of your variables, $myArray is actually a string, not an array. Also, $dataArray and $AnotherArray don't describe the data the variables are storing. When coding, it is useful to give variables meaningful names, so that yourself and others who may look at the code will find it easier to follow.

    点赞 评论 复制链接分享

相关推荐