AstrAir
AstrAir

Reputation: 13

PHP display a variable in a variable (string)

I have this code

$text = "Hello $person";
$persons = array("Mike", "Tom", "Foo");
foreach ($persons as $person) {
    echo $text."<br>";
}

The goal is to display:

Hello Mike<br>
Hello Tom<br>
Hello Foo<br>

I thought about using {} and $$, but that doesn't seem to be ok. What am I missing?

Upvotes: 0

Views: 89

Answers (6)

andrew-caulfield
andrew-caulfield

Reputation: 2070

This should achieve it.

    $persons = array("Mike", "Tom", "Foo");
      foreach ($persons as $person) {
         echo "Hello " . $person . "<br>";
      }

Upvotes: 2

invisal
invisal

Reputation: 11171

Let be a little creative, probably not the best, but it is one liner.

$persons = array("Mike", "Tom", "Foo");
echo vsprintf(str_repeat("Hello %s<br>", count($persons)), $persons);

Another one liner can be achieved with implode

echo "Hello" . implode("<br>Hello ", array("Mike", "Tom", "Foo")) . "<br>";

Note that my solution is not recommended, but it would be boring to have same answer as other people.

Upvotes: 0

Shashank Shah
Shashank Shah

Reputation: 2167

Just append hello using foreach the way i am doing is somehow very similar!

$persons = array("Mike", "Tom", "Foo");
      foreach ($persons as $person) {
      echo "Hello " . $person. "<br>";// Remove text and append Hello + break tag ofcourse
      }

Outputs:-

Hello Mike
Hello Tom
Hello Foo

Upvotes: 0

Adam Hull
Adam Hull

Reputation: 194

To make this simpler you could do

 $persons = array("Mike", "Tom", "Foo"); 
foreach ($persons as $person)
 { echo "hello".$person."<br>";
 }

Or you would do

   $text = "Hello";
    $persons = array("Mike", "Tom", "Foo");
     foreach ($persons as $person) 
    { 
    echo $text." ".$person."<br>"; 
    }

Upvotes: 0

HPierce
HPierce

Reputation: 7409

What am I missing?

You're assigning $text to a string that includes $person, but $person isn't defined yet (you should be getting a Notice: Undefined variable message). You could define $text within the loop, like many other answers suggest. But your code sample might look more familiar with sprintf:

$text = "Hello %s";
$persons = array("Mike", "Tom", "Foo");
foreach ($persons as $person) {
    echo sprintf($text, $person) . "<br>";
}

sprintf() will allow you to format a string by passing a parameter to it.

Upvotes: 3

Neobugu
Neobugu

Reputation: 333

Try this:

$persons = array("Mike", "Tom", "Foo");
foreach ($persons as $person) {
    $text = "Hello $person";
    echo $text."<br/>";
}

$text is outside foreach, for that reason $person wasn't echoed

Upvotes: -1

Related Questions