9

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

Run
  • 54,938
  • 169
  • 450
  • 748

9 Answers9

25

You need to use concatenation...

$string .= $value.',';

(notice the .)...

ircmaxell
  • 163,128
  • 34
  • 264
  • 314
9

Consider using implode for this specific scenario.

$string = implode(',', $employeeAges);
Brandon Horsley
  • 7,956
  • 1
  • 29
  • 28
7

You can also try

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

I tried that and it works.

Spontifixus
  • 6,570
  • 9
  • 45
  • 63
Mike
  • 71
  • 1
  • 2
3
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
  • 39,592
  • 10
  • 90
  • 121
2

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.

2

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
  • 1,101
  • 9
  • 7
1

Try this echo must be inside then {} became ok

    $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 - 28,16,35,46,34, - as the result

or other way

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

        }
            echo $string; 
Henok
  • 35
  • 6
1
$string .= $value.',';

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

You can use this verbose syntax:

$string = $string . $value . ',';
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
1

Input:

    $array = [1,2,3,4]

Save all data in one string:

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

Output:

    $string = '1,2,3,4,'

Remove last comma:

    $string =  rtrim($string, ',');

Output:

    $string = '1,2,3,4'

More information about:

concatenation;

rtrim.

Odin Thunder
  • 3,284
  • 2
  • 28
  • 47