0

In an app that I am building, I would like to create an array using contents that I have in a variable. This is my code:

$cont = '"q","w","e","r","t",';
$num = array(eval($cont));
foreach ($num as $v) {
    echo "" . $v . "<br>OK<br><br>";
}

It returns nothing. I tried it with the eval, and without What am I doing wrong?

xdazz
  • 158,678
  • 38
  • 247
  • 274

2 Answers2

1

Guess what you are looking after is explode() :

$cont = '"q","w","e","r","t","y"';
$num = explode(',',$cont);
foreach ($num as $v) {
    echo "" . $v . "<br>OK<br><br>";
}

outputs

"q"
OK

"w"
OK
..
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
  • 1
    If there is comma at last in string, it will print just "OK" in last. For that you can use array_filter() function to filter null values. – Kashyap Jan 06 '14 at 11:29
0

eval is evil, most of time. You can use preg_match_all instead:

$cont = '"q","w","e","r","t",';
preg_match_all("/\"([^\"]+)\"/", $cont, $matches);
$num = $matches[1];
foreach ($num as $v) {
    echo "$v<br>OK<br><br>";
}

Or simply create the array:

$num = array("q","w","e","r","t");
foreach ($num as $v) {
    echo "$v<br>OK<br><br>";
}

But if all these warnings and alternatives are not enough for you, and you insist on using eval, try this:

$cont = '"q","w","e","r","t",';
eval("\$num = array($cont);");
foreach ($num as $v) {
    echo "$v<br>OK<br><br>";
}
Community
  • 1
  • 1
evalarezo
  • 1,134
  • 7
  • 13