TripleDES Posted June 14, 2007 Share Posted June 14, 2007 The following code: for ($i = 0; $i < $varcount; $i = $i + 1) {echo "," . "\$parts[$i]";} Will output: ,$parts[0],$parts[1],$parts[2],$parts[3],$parts[4],$parts[5],$parts[6],$parts[7],$parts[8] What is a good way to append or save the resulting output to a variable? Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/55644-solved-loop-through-and-append-to-string/ Share on other sites More sharing options...
wildteen88 Posted June 14, 2007 Share Posted June 14, 2007 If you are dealing with an array and you want to place each array item into a string to be saved to a variavle use implode: <?php $parts = array('nuts and bolts', 'spanners', 'a chain'); $var = implode(', ', $parts); echo $var; ?> The result is a nice list like so: nuts and bolts, spanners, a chain Quote Link to comment https://forums.phpfreaks.com/topic/55644-solved-loop-through-and-append-to-string/#findComment-274942 Share on other sites More sharing options...
TripleDES Posted June 14, 2007 Author Share Posted June 14, 2007 Not quite what I'm looking for. I want a string because it will be used for a printr function like so: printf($cfgcontents . "\r",$parts[0],$parts[1],$parts[2],$parts[3],$parts[4],$parts[5],$parts[6],$parts[7],$parts[8]) so when it goes through the loop, I want each part appended to the string: $parts[0]....then $parts[1]...etc.... Quote Link to comment https://forums.phpfreaks.com/topic/55644-solved-loop-through-and-append-to-string/#findComment-275012 Share on other sites More sharing options...
kenrbnsn Posted June 15, 2007 Share Posted June 15, 2007 Instead of echoing the small string, append it to a variable: <?php $tmp = ''; for ($i = 0; $i < $varcount; $i = $i + 1) $tmp .= ',' . '$parts[' . $i . ']'; ?> Ken Quote Link to comment https://forums.phpfreaks.com/topic/55644-solved-loop-through-and-append-to-string/#findComment-275022 Share on other sites More sharing options...
TripleDES Posted June 15, 2007 Author Share Posted June 15, 2007 .= <-- This is it!! Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/55644-solved-loop-through-and-append-to-string/#findComment-275047 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.