0

I have a piece of php code that is submitting data to a database. Prior to that I do validation on other fields. If there are missing fields, I throw an error and echo the post data back to those fields.

I am using a jQuery plugin as well and need to send that data back the the plugin to re-invoke the tags.

 $("#tags").select2({
    tags: <?php if(isset($_POST['action'])) { 
                    if ($_GET['action'] != 'success'){ 
                        echo $_POST['tags']; }
                    }else{ 
                        echo '[]'; 
                    } ?>,
    minimumInputLength: 3,
    tokenSeparators: [",", " "]
});

It needs to be in this format:

["tag1", "tag2", "tag3"]

How can I achieve this from a comma separated string? tag1,tag2,tag3

0

2 Answers 2

2

If you are using PHP 5.2 or later, you can use json_encode to convert your object/array to json.

$tags = explode(',',$_POST['tags']);
echo json_encode($tags);

convert object/array to json http://www.php.net//manual/en/function.json-encode.php

Split string to an array by delimiter http://www.php.net//manual/en/function.explode.php

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the json_encode function:

echo json_encode( explode(',', $_POST['tags']) );

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.