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);
2
  • FYI, you want to concatenate the string inside the foreach loop. You wouldn't say that you want to concatenate a loop. Commented Sep 26, 2014 at 15:05
  • Where is your select tag? That's invalid markup. Commented Sep 27, 2019 at 4:14

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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
Sorry, I accidentally left a dot in there. I'll update with the complete code. Sometimes brevity is not helpful :)
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.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.