tags:

views:

35

answers:

2

I have a .php file that is rendering as a web page. Is there any way I could change a variable on the fly as the page renders?

Currently the page renders like this...

I love to eat oranges.
I love to eat oranges.
I love to eat oranges.

But I want it to render like this...

I love to eat oranges.
I love to eat apples.
I love to eat cheese.

Please see the sample code below...

<?php
$variable = "oranges";
?>

<?php
echo I love to eat $variable.
?>

<?php
$variable = "apples";
?>

<?php
echo I love to eat $variable.
?>

<?php
$variable = "cheese";
?>

<?php
echo I love to eat $variable.
?>
+1  A: 

You're missing some quotes and semicolons:

<?php
$variable = "oranges";
?>

<?php
echo "I love to eat $variable.";
?>

<?php
$variable = "apples";
?>

<?php
echo "I love to eat $variable.";
?>

<?php
$variable = "cheese";
?>

<?php
echo "I love to eat $variable.";
?>

Here's another way to accomplish the same thing:

<?php
    $foods = array('oranges', 'apples', 'cheese');
    $index = 0;
    function getFood($next = FALSE) {
       if($next) {
           $str = $foods[++$index];
       } else {
           $str = $foods[$index];
       }
       return 'I love to eat ' . $str; 
    }
?>

...

<?php
    echo getFood();
?>

...

<?php
    echo getFood(true);
?>

...

<?php
    echo getFood();
?>
Jacob Relkin
Or `echo "I love to eat " . $variable;`
Skilldrick
Thanks for your speedy reply.I'll actually be needing each variable to be called a number of times before it changes again...I love to eat oranges.I love to eat oranges.I love to eat oranges.I love to eat apples.I love to eat apples.I love to eat cheese.I love to eat cheese.I love to eat cheese.I love to eat cheese.How would the script cater for this?
Andy Cheeseman
Try my updated answer.
Jacob Relkin
Excellent! Thanks.
Andy Cheeseman
I know that it's a simplified example, but it won't work unless you set $index and $foods to be global variables (sic) in getNextFood().
Piskvor
I have tried putting the example code into a test .php file and It doesnt seem to work as is.How do I set them to global variables as @piskvor suggested?
Andy Cheeseman
+1  A: 

What is that, Programming 101?

<?php
foreach(array('apples','oranges','cheese') as $variable)
   echo "I love to eat $variable";
?>
ZJR
It should be array([...]) as $variable.
PatrikAkerstrand
`array(...) as $variable`, actually ;-)
Álvaro G. Vicario
yep, I'm doing javascript today, and didn't switch syntaxes :)
ZJR