Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 859
Run Avatar asked Aug 20 '10 17:08

Run


2 Answers

You need to use concatenation...

$string .= $value.',';

(notice the .)...

like image 169
ircmaxell Avatar answered Oct 03 '22 00:10

ircmaxell


Consider using implode for this specific scenario.

$string = implode(',', $employeeAges);
like image 31
Brandon Horsley Avatar answered Oct 03 '22 00:10

Brandon Horsley