0

Problem:

Converting a PHP string to a JSON array.

I have a string in PHP that looks like this:

intelligence skin weight volume

Desired output:

Is there a way in PHP where I can convert it so it looks like this instead:

["skin", "intelligence", "weight", "volume"]

I looked at json_encode() but that only put double quotes around the keywords.

5 Answers 5

4

If you want to create JSON array, you have to first explode your input string into an array.

Try with:

$input  = 'intelligence skin weight volume';
$output = json_encode(explode(' ', $input));
Sign up to request clarification or add additional context in comments.

Comments

2

first explode the string based on space. then u get an array containing individual words.then json_encode the array

$string="intelligence skin weight volume";
$array=explode(' ',$string);
$json=json_encode($array);

Comments

0

Check json_encode

This function would expect array and will convert array into json. Then use json_decode() to revert json to an array

Comments

0
$str="intelligence skin weight volume";
$arr=explode(' ',$str);
$json=json_encode($arr);

explode() used to split a string by a delimiter(in this senarion it is " ") Now you can encode the returend array as json.

Comments

0

Use json_encode

$jsonVal = json_encode(explode(' ', "intelligence skin weight volume"));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.