I'd like to create a string variable from an array.
Here's a non working code for conceptualizing it:
$list = array('elem1', 'elem2', 'elem3', 'elem4');
$myString = foreach ( $list as $element ){
'<span>' . $element . '</span><span>|</span>';
};
CodePudding user response:
You can do something like this
<?php
$lists = array("elem1", "elem2", "elem3", "elem4");
$string = '';
foreach ($lists as $element){
$string = $string . ' | '. $element;
};
echo '<span>' . $string . '</span>';
?>
CodePudding user response:
What you could do is concatenate the results of each iteration of your loop to a variable that exists outside of the loop.
Example:
$list = array('elem1', 'elem2', 'elem3', 'elem4');
$myString = '';
foreach ( $list as $element ){
$myString = $myString . '<span>' . $element . '</span><span>|</span>';
};
print($myString);
CodePudding user response:
$list = array('elem1', 'elem2', 'elem3', 'elem4');
foreach( $list as $element ){
$myString[] = '<span>' . $element . '</span><span>|</span>';
};
print(implode('', $myString));