0

I have a string which is stored like this:

["something", "someone", "anything", "anyone"]

Is there a direct function to convert something like this into an array? I tried eval() but it gave an unexpected end of file error.

4
  • what do you mean.. as in $string = '["something", "someone", "anything", "anyone"]';? if so, then just type cast it - var_dump((array) $string); Commented Dec 7, 2018 at 11:48
  • @treyBake yes that's how the string is stored. Thanks. I will try that. :) Commented Dec 7, 2018 at 11:49
  • 4
    You can try $string = '["something", "someone", "anything", "anyone"]'; $array = json_decode($string); var_dump($array); also Commented Dec 7, 2018 at 11:50
  • Try json_decode('["something", "someone", "anything", "anyone"]') Commented Dec 7, 2018 at 11:50

2 Answers 2

4

your value is like json you need just decode it like below code :

$string = '["something", "someone", "anything", "anyone"]'; 
$array = json_decode($string);
var_dump($array);

like @elmasterlow say in comment

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

Comments

1

For that example, you could do it with explode and a few str_replace calls:

$string = '["something", "someone", "anything", "anyone"]';
$string = str_replace("[","",$string);
$string = str_replace("]","",$string);
$string = str_replace('"',"",$string);
$array = explode(",",$string);
var_dump($array);

Also json_decode would work, as the comments stated:

$array = json_decode($string,true);

1 Comment

It is, no doubt. Just wanted to show an additional way.

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.