-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
Sherif
  • 11,786
  • 3
  • 32
  • 57
  • 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 – Memor-X Aug 30 '16 at 02:42

3 Answers3

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)
}
Sherif
  • 11,786
  • 3
  • 32
  • 57
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.

Community
  • 1
  • 1
Phil Wallach
  • 3,318
  • 20
  • 19
0

Use php-array-parser.

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

hacknull
  • 317
  • 1
  • 5