user1873432
user1873432

Reputation: 131

PHP converting Strings to Arrays back to Strings

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

Answers (6)

user1873432
user1873432

Reputation: 131

The answer was explode("\r\n", $result) but thanks for showing me the implode function everyone

Upvotes: 1

Useless Intern
Useless Intern

Reputation: 1302

$string = implode(" | ", $result);

Upvotes: 7

Deepak Mallah
Deepak Mallah

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

Henrique Barcelos
Henrique Barcelos

Reputation: 7900

To do this, you need the joinfunction: https://www.php.net/join

Upvotes: 2

bozdoz
bozdoz

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

bobwienholt
bobwienholt

Reputation: 17610

Try this:

implode("|", $string)

Upvotes: 7

Related Questions