2

I can't seem to wrap my head around this for some reason.

$welcome_message = "Hello there $name";

$names_array = array("tom", "dick", "harry");

foreach ($names_array as $this_name) {
    $name = $this_name;
    echo $welcome_message."<br>";
}

How do I update the $name variable within $welcome_message each time?

Using variable variables but I can't seem to make it work.

Thanks

1
  • Just make the $welcome_message assignment inside the loop. Commented Sep 22, 2012 at 17:01

3 Answers 3

6

Maybe you're looking for sprintf?

$welcome_message = "Hello there %s";

$names_array = array("tom", "dick", "harry");

foreach ($names_array as $this_name) {
    echo sprintf($welcome_message, $this_name), "<br>";
}
Sign up to request clarification or add additional context in comments.

3 Comments

How to handle it if there are different parts of the $welcome_message that need to be customized? For instance "Hello there %s, the temperate right now is <temp>"
Read up on the *printf function family (start here ). In short: you can have multiple placeholders in a single string, and they can be of different formats. Your code needs a string placeholder (%s), but there others for decimals, floats, chars and many more.
echo sprintf() is an "antipattern". There is absolutely no reason that anyone should ever write echo sprintf() in any code for any reason -- it should be printf() without echo every time.
5

This won't work because $welcome_message is evaluated just once, at the beginning (when $name is probably still undefined). You cannot "save" the desired form inside $welcome_message and "expand" it later at will (unless you use eval, and that's something to be totally avoided).

Move the line that sets $welcome_message inside the loop instead:

$names_array = array("tom", "dick", "harry");

foreach ($names_array as $this_name) {
    $welcome_message = "Hello there $this_name";
    echo $welcome_message."<br>";
}

2 Comments

The issue is my $welcome_message is a lot bigger than in my simple example. If its big, in a loop, I was thinking of performance issues when trying to have it outside of the loop.
@phpmysqlguy: You need to substitute variables into the message on each iteration. No matter how you choose to do it, the fact is that you cannot magically avoid this.
3

you can update the $welcome_message each time like this....

$welcome_message = "Hello there ".$name;

now the code will be like this...

$welcome_message = "Hello there ";

$names_array = array("tom", "dick", "harry");

foreach ($names_array as $this_name) {
echo $welcome_message.$this_name"<br>";
}

1 Comment

I think I failed to mention that the $welcome_message is a lot bigger, and has numerous parts that need changing. It's not as simple as I let on, I was trying to simplify for the purposes of this example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.