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
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
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.
return array(1,2,3,4,5,6);
$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) }
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.
Use php-array-parser.
But it's not working well with different types of tokens in the same time, e.g. "array()" and "[]".