Page 1 of 1

foreach: put each of the loop result in one variable

Posted: Fri Aug 20, 2010 12:46 pm
by lauthiamkok
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

Re: foreach: put each of the loop result in one variable

Posted: Fri Aug 20, 2010 1:26 pm
by oscardog

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);

Re: foreach: put each of the loop result in one variable

Posted: Fri Aug 20, 2010 1:28 pm
by buckit

Code: Select all

$string .= $value.',';
= creates the variable and sets the value
.= appends the variable with the specified value.

Re: foreach: put each of the loop result in one variable

Posted: Fri Aug 20, 2010 1:39 pm
by lauthiamkok
buckit wrote:

Code: Select all

$string .= $value.',';
= creates the variable and sets the value
.= appends the variable with the specified value.
thanks so much! :D

Re: foreach: put each of the loop result in one variable

Posted: Fri Aug 20, 2010 1:40 pm
by lauthiamkok
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! :D

Re: foreach: put each of the loop result in one variable

Posted: Fri Aug 20, 2010 1:44 pm
by John Cartwright
Best option would be to implode() the array values.

Code: Select all

$ages = implode(', ', $employeeAges);
echo $ages;

Re: foreach: put each of the loop result in one variable

Posted: Fri Aug 20, 2010 1:51 pm
by lauthiamkok
John Cartwright wrote:Best option would be to implode() the array values.

Code: Select all

$ages = implode(', ', $employeeAges);
echo $ages;
thank you :D