1

How can I concat a string inside a for each loop? What I'm doing below works ok without the loop, but is there a way I can put the loop in there without ending the $body[{{body}}] and starting it again?

$carrier = array (
    'SAS' => array('alias' => 'sas', 'name' => 'SAS'),
    'British Airways' => array('alias' => 'british_airways', 'name' => 'British Airways')
);

$body['{{body}}'] = '';

$body['{{body}}'] .= 'Line one'.

    foreach ($carrier as $key=>$value) {
        '<option value='.$value['alias'].'>'.$value['name'].'</option>'.;
    }

'Line two'.
'Line three'.
'Line four';

print_r($body);
Grice
  • 1,345
  • 11
  • 24
jmenezes
  • 1,888
  • 6
  • 28
  • 44

2 Answers2

7

Try this - you have to concatenate each line generated in the foreach loop.

$carrier = array (
    'SAS' => array('alias' => 'sas', 'name' => 'SAS'),
    'British Airways' => array('alias' => 'british_airways', 'name' => 'British Airways')
);

$body['{{body}}'] = 'Line one';

foreach ($carrier as $key=>$value) {
    $body['{{body}}'] .= '<option value=' . $value['alias'] . '>' . $value['name'] . '</option>';
}

$body['{{body}}'] .= 'Line two';
$body['{{body}}'] .= 'Line three';
$body['{{body}}'] .= 'Line four';

print_r($body);
Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
  • Still the same. There are line after the foreach too. `Parse error: syntax error, unexpected T_FOREACH in C:\web\apache\htdocs\esp\test\concat.php on line 12` – jmenezes Sep 26 '14 at 15:11
  • Sorry, I accidentally left a dot in there. I'll update with the complete code. Sometimes brevity is not helpful :) – Surreal Dreams Sep 26 '14 at 15:14
  • Now I've posted the complete code. Notice that I simplified the initialization of `$body['{{body}}']`. Each line that starts with `$body['{{body}}'] .=` ends with a semicolon. I've not tested it (no php environment, sorry), but I would expect it to work. – Surreal Dreams Sep 26 '14 at 15:22
3
$word = 'foo';
$result = "";
$char_buff = str_split($word);

foreach ($char_buff as $char){
  $result .= $char;
}

echo var_dump($result);

Which outputs the following:

string(3) "foo"

How to combine strings inside foreach into single string PHP

Nurseyit Tursunkulov
  • 8,012
  • 12
  • 44
  • 78