views:

35

answers:

6

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,

$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

+3  A: 

You need to use concatenation...

$string .= $value.',';

(notice the .)...

ircmaxell
thanks so much! :-)
lauthiamkok
A: 
$string .= $value.',';

Use the concatenation, put a dot before the equal sign.

You can use this verbose syntax:

$string = $string . $value . ',';
Sarfraz
thanks so much! :-)
lauthiamkok
A: 
foreach( $employeeAges as $key => $value){
    $string .= $value.',';
}

You are resetting your string variable each time through your loop. Doing the above concatenates $value to $string for each loop iteration.

Tommy
thanks so much! :-)))
lauthiamkok
A: 

Um, what about this?

$string = "";
foreach( $employeeAges as $key => $value){
    $string .= $value.',';
}

You are resetting the variable each time, this starts with the empty string and appends something each time. But there are propably betters ways to do such tasks, like implode in this case.

delnan
thank u very much! :-)
lauthiamkok
A: 

Try

$string = '';
foreach( $employeeAges as $key => $value){
    $string .= $value.',';
}

With $string = $value.','; you are overwriting $string every time, so you only get the last value.

Zaki
thanks so much! :-)
lauthiamkok
+7  A: 

Consider using implode for this specific scenario.

$string = implode(',', $employeeAges);
Brandon Horsley
a good idea! thank you :-))
lauthiamkok