-1

I have string representation of an array in a file. I need to convert it to array . How to achieve this.

For example

$arr = 'array(1,2,3,4,5,6)'; 

echo getType($arr); // string

//convert $arr to type array

echo getType($arr); // array
1
  • if there a particular reason why the string is like that? if it wasn't for the ' on either end it would be an array Commented Aug 30, 2016 at 2:42

3 Answers 3

0

It depends on if the file is made up entirely of valid PHP. If it is you could just include the file. Otherwise, given that this string is valid PHP you could eval the string, though typically this is viewed as bad solution to almost any problem.

If the entire file is valid PHP and you just want the array in another script use include.

somefile.php

return array(1,2,3,4,5,6);

someotherfile.php

$arr = include 'somefile.php';
var_dump($arr);

This gives you...

array(6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Above solution helped me.
0

I don't know if the string format is fixed or not.

If not you could look at serialize() and unserialize().

The other approach, assuming the format is as written, would be to execute the file, through require or include, rather than read it as a string. That would create the variable in your context. There are a few little issues with this approach, such as enclosing tags, but perhaps that is resolvable in your situation.

Lastly I found this approach as well: Execute PHP code in a string. This is an improved variant of my second approach.

Comments

0

Use php-array-parser.

But it's not working well with different types of tokens in the same time, e.g. "array()" and "[]".

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.