1

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

2
  • 1
    Unnormalized database // SQL join smell. Commented May 17, 2013 at 15:18
  • implode() is what you want; it does exactly what you're asking for. If you're not seeing that then there's something else going on with your array that you haven't told us. Commented May 17, 2013 at 15:37

6 Answers 6

7

Try this:

implode("|", $string)
Sign up to request clarification or add additional context in comments.

2 Comments

The first element of your array must be an empty string, or a space or something. What does print_r($string) show?
Just add spaces to the " | " and use trim() to take the leading and trailing space off.
7

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

Comments

5

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 | 
?>

2 Comments

bozdoz, instead of spaces, they are actually a new line "\n" please try that.
The link has been updated, but it's the same result. @user1873432
2

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

Comments

2

if $string is the array than you can use implode to convert it into string Try this

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

1 Comment

now I am trying to put that array back into a single string having a | seperator This is what you asked, you mentioned separator
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.