'create a string variable with all of an array's items [duplicate]
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>';
};
Solution 1:[1]
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>';
?>
Solution 2:[2]
$list = array('elem1', 'elem2', 'elem3', 'elem4');
foreach( $list as $element ){
$myString[] = '<span>' . $element . '</span><span>|</span>';
}
print(implode('', $myString));
Solution 3:[3]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rolando Velazquez |
| Solution 2 | DarkBee |
| Solution 3 | IMSoP |
