php foreach: put each of the loop result in one variable
41,900
Solution 1
You need to use concatenation...
$string .= $value.',';
(notice the .
)...
Solution 2
Consider using implode for this specific scenario.
$string = implode(',', $employeeAges);
Solution 3
You can also try
$string = '';
foreach( $employeeAges as $value){
$string .= $value.',';
}
I tried that and it works.
Solution 4
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.
Solution 5
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.
Comments
-
Run almost 4 years
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
-
utdev about 7 yearsHow would you remove the last ','