开发者

php array() w/ foreach only loops if using .= to build the result

I have a very frustrating problem which I cannot result. Its just not adding up.

I am passing an array to process on a foreach() like so:

if (is_array($seminar)) {
foreach ($seminar as $sem_id)
    $sem_id_list .= "$sem_id";
    echo "$sem_id<br />";
}

As you can see my array() is $seminar, and that output looks like so:

Array
(
    [0] => 3
    [1] => 8
    [2] => 9
    [3] => 13
    [4] => 14
    [5] => 15
)

As you can see in my code, I am building a block w/ =. like: *$sem_id_list .= "$sem_id";* and the when echoed out looks like: 389131415 as expected.

BUT when I simply trying to iterate through and print each value like: *echo "$sem_id

";* I only get the last array() item!!

I've never run 开发者_如何转开发into this problem before. I am guessing I am missing something dead simple here, but from all my experience this should be working and printing those results just fine.

As a side note, var_dump($seminar); produces this too:

array(6) { [0]=> string(1) "3" [1]=> string(1) "8" [2]=> string(1) "9" [3]=> string(2) "13" [4]=> string(2) "14" [5]=> string(2) "15" }


You're missing the opening brace of the foreach and a closing brace. Try:

if (is_array($seminar)) {
  foreach ($seminar as $sem_id) {
    $sem_id_list .= "$sem_id";
    echo "$sem_id<br />";
  }
}

or build the list and print it at the end:

if (is_array($seminar)) {
  foreach ($seminar as $sem_id) {
    $sem_id_list .= "$sem_id";
  }
  echo "$sem_id_list";
}


you are missing {} for your loop check

  if (is_array($seminar)) {
foreach ($seminar as $sem_id){
    $sem_id_list .= "$sem_id";
    echo "$sem_id<br />";
}
}

http://codepad.org/0UZpQOZx

If you don't give {} there will be only one statement in your loop which is

   $sem_id_list .= "$sem_id";

and line echo "$sem_id<br />"; will only executed once after completion of loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜