PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
lauthiamkok
Forum Contributor
Posts: 153 Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom
Post
by lauthiamkok » Fri Aug 20, 2010 12:46 pm
Hi,
I think this is probably a very simple but I can get my head around! How can I put each of the loop result in one variable only? for instance,
Code: Select all
$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";
foreach( $employeeAges as $key => $value){
$string = $value.',';
}
echo $string;
// result 34,
// but I want to get - 28,16,35,46,34, - as the result
Many thanks,
Lau
oscardog
Forum Contributor
Posts: 245 Joined: Thu Oct 23, 2008 4:43 pm
Post
by oscardog » Fri Aug 20, 2010 1:26 pm
Code: Select all
foreach( $employeeAges as $key => $value){
$string .= $value . ',';
}
(Notice there is a full stop before the equals sign)
And if you want to remove the last comma from the string...
Code: Select all
foreach( $employeeAges as $key => $value){
$string = $value.',';
}
$string = substr($string, 0, strlen($string) - 1);
buckit
Forum Contributor
Posts: 169 Joined: Fri Jan 01, 2010 10:21 am
Post
by buckit » Fri Aug 20, 2010 1:28 pm
= creates the variable and sets the value
.= appends the variable with the specified value.
lauthiamkok
Forum Contributor
Posts: 153 Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom
Post
by lauthiamkok » Fri Aug 20, 2010 1:39 pm
buckit wrote:
= creates the variable and sets the value
.= appends the variable with the specified value.
thanks so much!
lauthiamkok
Forum Contributor
Posts: 153 Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom
Post
by lauthiamkok » Fri Aug 20, 2010 1:40 pm
oscardog wrote: Code: Select all
foreach( $employeeAges as $key => $value){
$string .= $value . ',';
}
(Notice there is a full stop before the equals sign)
And if you want to remove the last comma from the string...
Code: Select all
foreach( $employeeAges as $key => $value){
$string = $value.',';
}
$string = substr($string, 0, strlen($string) - 1);
thank you and thanks for tidying up my code!
John Cartwright
Site Admin
Posts: 11470 Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:
Post
by John Cartwright » Fri Aug 20, 2010 1:44 pm
Best option would be to implode() the array values.
Code: Select all
$ages = implode(', ', $employeeAges);
echo $ages;
lauthiamkok
Forum Contributor
Posts: 153 Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom
Post
by lauthiamkok » Fri Aug 20, 2010 1:51 pm
John Cartwright wrote: Best option would be to implode() the array values.
Code: Select all
$ages = implode(', ', $employeeAges);
echo $ages;
thank you