1

If I implode an array $arr = ["Hello my, name is Steve", "How are you?"] to string to insert to MySQL database like so: $data = implode(',',$arr);, when I try to retrieve those values and explode it back into array: $arr2 = explode(',',$data); it returns : ["Hello my", "name is Steve", "How are you?"]

How do I get it to ignore the comma thats already in between quotes and explode as:

["Hello my, name is Steve", "How are you?"]

5
  • 1
    In a case like that, I'd suggest using a character not commonly found in a string, such as | Commented Feb 24, 2020 at 19:30
  • 4
    You should normalize your database design so that you don't store comma separated values. Alternatively use JSON instead. Commented Feb 24, 2020 at 19:31
  • @aynber The string comes from user input in a form, so should I just append a unique character to the end of the input so it can seperate from there? Commented Feb 24, 2020 at 19:34
  • I meant use | for the imploding/exploding character, so you don't change the user input. But I agree with Nigel, using json would be a lot easier. Commented Feb 24, 2020 at 19:36
  • Not every PHP scripts needs to involve implode/explode. Sometimes it's perfectly reasonable to keep JSON as storage format, if preserving structure is beneficial. xyproblem.info Commented Feb 24, 2020 at 20:02

1 Answer 1

1

Instead you can use json_encode and json_decode.

Try this out:

$arr = ["Hello my, name is Steve", "How are you?"]
$data = json_encode($arr); //Insert $data into mysql 
//Then to retrieve values 
$arr2 = json_decode($data); //returns ["Hello my, name is Steve", "How are you?"]
Sign up to request clarification or add additional context in comments.

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.