2

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";
}

6 Answers 6

13

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Or sprintf() if you don't actually want to echo it. +1
@Mchl Thanks; incorporated into the answer
or vsprintf() if you want to add arguments dynamically (for the i8n you most likely would) :-P
0

Use str_replace.

For example:

$str = "This is [VARIABLE] is delicious";
$array = array("Apple", "Pineapple", "Strawberry");

foreach($array as $variable)
{
    print str_replace('[VARIABLE]', $variable, $str);
}

1 Comment

@stereofrog: It's possible to swap order of variables in (v|s)printf(). See example #3 here: php.net/manual/en/function.sprintf.php
0

Why don't you just do:

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

foreach($array as $variable) {
    print "This $variable is delicious";
}

1 Comment

That would work. But this isn't the actual code I'm working with. I just used it for the purpose of the example.
0

I think you need php's sprintf function

http://php.net/manual/en/function.sprintf.php

or it can also be done using str_replace

http://in.php.net/manual/en/function.str-replace.php

Comments

0

You are probably doing wrong way.
Learn to use templates and you will never need such odd things.
Just divide your code into 2 parts:

  • getting all required information
  • displaying a regular page or an error page

you will find that all your code become extremely neat and reusable

1 Comment

The OP might be using this for i8n
-2
$str='This $variable is delicious'; // so no variable interpolation is performed

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

foreach($array as $variable)
{
  // Warning! This is a very bad idea!
  // Using eval or system might create vulnerabilities!
  eval('$str="' . $str . '";');
  print $str;
}

1 Comment

This is a bad idea indeed. Not worth downvoting though, because it's noted on the answer it's a bad idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.