Wagtail Posted March 25, 2014 Share Posted March 25, 2014 Hello forum members, is it possible to assign the contents of a foreach loop to a variable? I am looping out some names. If the foreach loop loops out 5 names, then I'd like all 5 names to be assigned to the $names variable. I think this was working yesterday but perhaps I was imagining things. $names = ''; foreach($names as $k => $v){ $names .= "<p>$v</p>"; } echo $names; Thank you for your help. Link to comment Share on other sites More sharing options...
HartleySan Posted March 25, 2014 Share Posted March 25, 2014 Make $names an array, and then you're good: $names = array(); foreach($list_of_names as $name) { $names[] = $name; } Note that I didn't use $names as the first parameter of the foreach loop. That's important. Link to comment Share on other sites More sharing options...
Wagtail Posted March 25, 2014 Author Share Posted March 25, 2014 HartleySan, thank you for helping me! It's working. I couldn't understand what the problem was until I saw that I had initialized $names after the foreach loop had already begun. But don't tell anyone... Thanks again. Cheers Link to comment Share on other sites More sharing options...
HartleySan Posted March 25, 2014 Share Posted March 25, 2014 "Don't tell anyone"? Isn't this a public forum? Anyway, glad it worked. Link to comment Share on other sites More sharing options...
Recommended Posts