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?

3
  • That code doesn't make any sense Commented Jan 6, 2014 at 2:14
  • php.net/explode PS: instead of developing custom serialization algorithms it makes sense to check json instead. Commented Jan 6, 2014 at 2:18
  • 1
    You can't eval a random half-formed expression. It has to be valid PHP. Commented Jan 6, 2014 at 2:23

2 Answers 2

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
..
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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>";
}

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.