printing variables within a variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jaymoore_299
Forum Contributor
Posts: 128
Joined: Wed May 11, 2005 6:40 pm
Contact:

printing variables within a variable

Post by jaymoore_299 »

is there a way to print the variables within a variable?

Code: Select all

$a="a"
$b="b"
$c="c"
$vars = "text".$a."text".$b."text".$c
print $vars
// so that it outputs: "textatextbtextc"
// just as though I sent it
print "text".$a."text".$b."text".$c;
$vars will be used as a customizable combination of string and variables so that print would show them as though the contents of $vars was sent,

JCART | Please use

Code: Select all

tags when posting php code. Review [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color][/size]
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Code: Select all

echo "text{$a}text{$b}text{$c}";
jaymoore_299
Forum Contributor
Posts: 128
Joined: Wed May 11, 2005 6:40 pm
Contact:

Post by jaymoore_299 »

The contents of $var will have any number of different combinations of variables that I will not know in advance so that won't work.
Syranide
Forum Contributor
Posts: 281
Joined: Fri May 20, 2005 3:16 pm
Location: Sweden

Post by Syranide »

best example that works pretty flawlessly (and fast) for this is simple str_replace or preg_replace...

takes a list of "keys", and what they should be changed too.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

You might want to read http://php.belnet.be/manual/en/functions.arguments.php

It allows you to specify your own function with a variable number of arguments.
Something like (untested)

Code: Select all

function myecho()
{
  foreach(func_get_args() as $name => $val)
  {
    echo "$val";
  }
}

myecho("text", $a, "text", $b, "text", $c);
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Getting a bit confused with what you are actually asking for.

Code: Select all

$var=&quote;testa&quote;;
$testa=&quote;Hello&quote;;
echo($$var);
who output "Hello". Don't know if that is any use to you.
Post Reply