Skip to content
Advertisement

How to convert the string representation of array to normal array

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

Advertisement

Answer

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)
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement