Home > Mobile >  PHP variables in a String
PHP variables in a String

Time:11-04

I have a string that contains variables in it, and I want to add the values of the variables into it, as I'm trying it, it simply spits out as a string instead of adding the values of the variables.

Here is my code

$vars = $item->toArray();

    extract($vars);
    echo ($message_tmpl);die;

    echo print_r($message_tmpl)die;

Variables are extracted to add the values, but it returns plain output instead of values.

$first_name is extracted through $vars

Output
'My message to $first_name';

It should be
'My message to John Doe';

thanks

CodePudding user response:

you can do this :

$name = "Toto";

$info["age"] = "8yo";

echo "Hello {$name} who is {$info["age"]}";

will output :

Hello Toto who is 8yo

You can also use the strtr() function such as :

$template = '$who likes $what';

$vars = array(
  '$who' => 'Toto',
  '$what' => 'fruits',
);

echo strtr($template, $vars);

you will get : Toto likes fruits

  • Related