[SOLVED] Execute a string in PHP?

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
tonic889
Forum Newbie
Posts: 8
Joined: Fri Apr 16, 2004 9:07 pm

Execute a string in PHP?

Post by tonic889 »

Here is my situation. I have some variables in a php program:

$foo1 = "stuff";
$foo2 = "more stuff";
...
$foo50 = "end of stuff";

What I would like to know is if there is a command in PHP to instruct PHP to execute a given string in PHP. So in other words,

<?

$i = 0;
while ($i < 50) {
execute_command("echo $foo" . $i);
i++;
}

?>

..would cause php to execute the commands "echo $foo1", "echo $foo2", etc... The end result of the program would then be:

stuff
more stuff
...
end of stuff.

My question is: Is there a command like "execute_command" (this was just a name I made up) that will do what I've described?

Hope this makes sense...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

[php_man]eval[/php_man](), however, what you want to do can be done without eval..

Code: Select all

<?php

echo ${'foo' . $i};

?>
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Post by d3ad1ysp0rk »

Am I missing something?

What's wrong with:

Code: Select all

$i = 0;
while ($i < 50) {
  echo $foo . $i;
  $i++;
}
tonic889
Forum Newbie
Posts: 8
Joined: Fri Apr 16, 2004 9:07 pm

Post by tonic889 »

Lilpunk - When I tried your code, I got just the value of i outputed (ie. 0123456789....etc.)

Feyd - your code worked fine.

Thanks both of you for your replies.
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Post by d3ad1ysp0rk »

ohhh, i just understood it, sorry it was kinda 3am :P
Post Reply