Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include a yet to be defined variable inside a string? PHP

Tags:

variables

php

For sake of performing less database queries and for clarity of code, I'd like include a yet to be defined variable inside a string. Later in the page, the variable will be declared and the string printed and evaluated. How do i do this?

$str="This $variable is delicious";

$array=array("Apple","Pineapple","Strawberry");

foreach($array as $variable)
{
  print "$str";
}
like image 387
matt Avatar asked Jul 15 '26 01:07

matt


1 Answers

You can use printf() (or sprintf() if you don't want to echo it):

$str = 'This %s is delicious';

foreach ($array as $variable) {
    printf($str, $variable);
}
like image 98
NullUserException Avatar answered Jul 17 '26 14:07

NullUserException



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!