I have loads of constants set. I have phrases from database that might have those constant names in them.
I want to replace the constants names with their values.
Constants:
Array
(
[WORK1] => Pizza Delivery
[WORK2] => Chauffer
[WORK3] => Package Delivery
)
Variables:
$variable[0] = "I like doing WORK1";
$variable[1] = "Nothing here mov开发者_如何转开发e along";
$variable[2] = "WORK3 has still not shown up.";
How would I get those variables with the right constant vales on them? Constants order could be unsorted as well as variables.
Should be as simple as:
foreach ($variable as &$v)
{
$v = str_replace(array_keys($constants), array_values($constants), $v);
}
unset($v);
Note that it is probably more optimal to do something like this before the loop:
$keys = array_keys($constants);
$vals = array_values($constants);
And then use them directly instead of calling array_key/vals during every iteration.
And on second thought, this is probably best:
foreach ($variable as &$v)
{
$v = strtr($v, $constants);
}
unset($v);
because it doesn't process first to last, and you should get consistent behavior regardless of how the constants are sorted.
精彩评论