Jump to content

Echo variable that gets generate LATER


StevenOliver

Recommended Posts

What's the method to echo a variable that won't get created until later?

Example:

echo "A lucky day for you is $day_of_week";

echo "blah blah blah";

$items = array('Sunday','Monday','Tuesday','Wednesday','Thursday');
$day_of_week = $items[array_rand($items)];

 

I don't need to code anything this way (yet). But I remember reading years ago how to do something like this -- I just can't remember now, nor can I find anything on the net about this. I do recall this can be done somehow with output buffering, ob_start(), etc., but I've been experimenting all afternoon and can't solve this puzzle...

 

 

 

 

Link to comment
Share on other sites

37 minutes ago, benanamen said:

And you think you will? If something doesn't exist how do possibly expect to output it?

...by capturing the echo statement in a buffer, adding the variable to it, then flushing. I saw this done somewhere. I just cannot re-create it now. Here is a non-elegant way of doing this:

ob_start();
echo "A lucky day for you is ___";

$capture=ob_get_clean();
$items = array('Sunday','Monday','Tuesday','Wednesday','Thursday');
$day_of_week = $items[array_rand($items)];

echo str_replace('___',$day_of_week,$capture);

Link to comment
Share on other sites

Like @requinix said but....

 

<?php
function foo($day_of_week){
 echo "A lucky day for you is $day_of_week";
}

ob_start();
$day_of_week = 'Tuesday';
foo($day_of_week);

$output = ob_get_clean();
echo $output;

Same thing can be done like

<?php
function foo($day_of_week){
 return "A lucky day for you is $day_of_week";
}

$day_of_week = 'Tuesday';
$output = foo($day_of_week);
echo $output;

But really though, what is the REAL problem you need to solve?

Link to comment
Share on other sites

Can you please explain why one would want to output something that they haven't assigned a value to yet?  The code you posted shows us no reason to do the echo prior to setting your value, so it makes absolutely no sense.

A good way around all this discussion would be to do the proper thing.  Write your script where the php is done first, then the html is output - from the doctype line through to the end of your output.  Don't mix them together except where you may have to loop thru some data in order to build the needed output (an html table?).  In those cases simply assign the html to a var and then place that var in the html code that you output later on.  End of issue.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.