1
$var = "['test', 'test2', 'test3']";

how do I create a workable array from this in PHP?

I've tried explode($var, ","); but this didn't seem to work, unless something went wrong with that attempt.

3
  • It's always a bad idea to store code in strings like this! $myArray = str_getcsv(trim($var, '[]'), ',', "'"); Commented Jun 1, 2015 at 8:15
  • Is there any reason that you can't just json_decode that? Commented Jun 1, 2015 at 9:22
  • Ah yeah, singlequotes... Commented Jun 1, 2015 at 9:24

4 Answers 4

3

explode($var, ","); is wrong. explode needs the first argument to be the delimiter and the second be the string. Replace [] and then explode -

$var = "['test', 'test2', 'test3']";

$var = str_replace(array('[', ']'), '', $var);
$arr = explode(',', $var);
Sign up to request clarification or add additional context in comments.

Comments

1
 [akshay@localhost tmp]$ cat test.php
 <?php 
 $var = "['test', 'test2', 'test3']";
 print_r(  json_decode(str_replace("'","\"",$var)) );
 ?>

Output

 [akshay@localhost tmp]$ php test.php
 Array
 (
     [0] => test
     [1] => test2
     [2] => test3
 )

Comments

1

I would say that it looks like a job for json_decode, but its not valid json... There is a way to make it valid however:

How to json_decode invalid JSON with apostrophe instead of quotation mark

Comments

0

There is an eval() function in PHP which converts string into PHP statements. The string has to be valid PHP statement.

In your case "['test', 'test2', 'test3']"; is not valid statement. You can use something similar to below syntax. Please note that the $x is in single quotes as $x in double quotes will return the value.

$var = "['test', 'test2', 'test3'];"; eval('$x = ' . $var); print_r($x);

2 Comments

Then just pray that this isn't input from a user or 3rd party. I wouldn't use eval for this.
Yea that's true; it could be vulnerable to attacks if the string is user input and not sanitized properly.

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.