I have a foreach loop in a PHP script that outputs icons / links from a database. I've used this question to use str_replace to change some values after the icons are rendered.
foreach ($icons as $ic)
{ echo str_replace('{{EMP_NO}}', $_SESSION['EmpNo'], $ic['url']) . ' '; }
I need to do a similar operation on a value {{FIRST_NAME}} but when I append with a second str_replace the second command / value is ignored. Like this:
foreach ($icons as $ic)
{ echo str_replace('{{EMP_NO}}', $_SESSION['EmpNo'], $ic['url']) . ' '; }
{ echo str_replace('{{FIRST_NAME}}', $_SESSION['FirstName'], $ic['url']) . ' '; }
When I try to combine them like this it doubles the icons output which I don't want:
foreach ($icons as $ic) { echo str_replace('{{EMP_NO}}', $_SESSION['EmpNo'], $ic['url']) . ' '; echo str_replace('{{FIRST_NAME}}', $_SESSION['FirstName'], $ic['url']) . ' '; }
How do I also str_replace {{FIRST_NAME}}?
str_replace
can replace array of values to array of other values:
foreach ($icons as $ic) {
echo str_replace(
array('{{EMP_NO}}', '{{FIRST_NAME}}'),
array($_SESSION['EmpNo'], $_SESSION['FirstName']),
$ic['url']) . ' '
);
}
And as already mentioned in @David's answer, though your code has a correct syntax, but its' logic is flawed.
You've structured your loop incorrectly. If you re-align the brackets, you see that you have this:
foreach ($icons as $ic)
{
echo str_replace('{{EMP_NO}}', $_SESSION['EmpNo'], $ic['url']) . ' ';
}
{
echo str_replace('{{FIRST_NAME}}', $_SESSION['FirstName'], $ic['url']) . ' ';
}
Basically, you've given the same loop two bodies. What that actually does is execute the first body as the loop itself, then the second "body" (block of code in random curly braces) is simply executed once after the loop, like any other code.
A loop has only one body:
foreach ($icons as $ic) {
echo str_replace('{{EMP_NO}}', $_SESSION['EmpNo'], $ic['url']) . ' ';
echo str_replace('{{FIRST_NAME}}', $_SESSION['FirstName'], $ic['url']) . ' ';
}
Edit: Based on a comment below, it sounds like you really only want to output one line instead of two. In that case you don't want to echo
twice. But you do still want to replace twice. A first pass might just take the output of the first str_replace()
as the input for the second. However, str_replace()
also accepts arrays (so it internally "replaces twice"):
foreach ($icons as $ic) {
echo str_replace(array('{{EMP_NO}}', '{{FIRST_NAME}}'), array($_SESSION['EmpNo'], $_SESSION['FirstName']), $ic['url']) . ' ';
);
(Note: It looks like another answer suggests this as well while I was creating this one.)