Reputation: 131
I am pulling data from a query that has the following output: 1 2 3 5
I am converting it into an array like so:
$string = explode("\n", $result);
I know have an array displaying the following:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 5
)
now I am trying to put that array back into a single string having a | seperator
$test = "";
foreach($string as $key)
{
$test .= $key." | ";
}
however, I am getting the ouput of test:
| 5 |
can somone explain why its not showing what I expect it to show and another way how to produce a single string with a | seperator?
thanks
Upvotes: 1
Views: 157
Reputation: 131
The answer was explode("\r\n", $result) but thanks for showing me the implode function everyone
Upvotes: 1
Reputation: 4076
if $string is the array than you can use implode to convert it into string Try this
$new_string = implode("|", $string);
Upvotes: 2
Reputation: 7900
To do this, you need the join
function:
https://www.php.net/join
Upvotes: 2
Reputation: 12860
I would think implode would be what you're looking for.
Also, to comment on why your code is not working, I'm not sure. Check out this example on ideone.com: http://ideone.com/rH3qbr. I copied your code and it seems to be working, I think, as you would expect it to.
<?php
$result = '1 2 3 4 5';
$string = explode(" ", $result);
$test = "";
foreach($string as $key) {
$test .= $key." | ";
}
echo $test; // outputs 1 | 2 | 3 | 4 | 5 |
?>
Upvotes: 5