Im creating a web app where I want all of the responses to the user stored in a language file for easy editing. So Im using eval() to manage dynamic messages lik so:
$msg = 'Hello $user, your favorite color is $color';
$colors = array("red","green","blue","yellow");
$users = array("bob","craig","ted","dirty sanchez");
foreach($users as $key => $user){
$color = $colors[$key];
eval("\$newmsg = \"$msg\";");
echo $newmsg;
}
Im wondering if this is the best approach or if there is a better way?
Never use that damn eval if not necessary! Your code won't work, you should use sprintf for your purpose.
$messageFormat = 'Hello %s, your favorite color is %s';
$colors = array("red","green","blue","yellow");
$users = array("bob","craig","ted","dirty sanchez");
foreach($users as $key => $user){
$color = $colors[$key];
$actualMessage = sprintf($messageFormat, $user, $color);
echo htmlentities($actualMessage);
}
Assuming you're using this for comments or other user-supplied text, I've added htmlentities()
to prevent XSS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With