charlie
charlie

Reputation: 1384

how to echo a PHP variable before it has been declared

I have a HTML button:

<button>Button Name</button>

below the button i have a div which i am requiring a file in:

<div id="my_div"><?php require_once 'file.php'; ?></div>

in the file.php file i have a PHP variable, i want to echo this variable on the button name (Button Name var_here)

but its not showing the variable as the variable is being declared after i echo it

is there any way round this?

Upvotes: 2

Views: 1281

Answers (6)

charlie
charlie

Reputation: 1384

I have sorted this now. In the required file rather than echoing the results creating a new variable ($var_display.= ...) then echoing $var_display under the HTML button

The file Is being required right at the top of the page

Upvotes: 0

Charles Harmon
Charles Harmon

Reputation: 380

Something about this design doesn't sit right with me, you usually include all your php up top, but I understand that for layout reasons you may want to go this way.

One way around it is to set this via javascript. This is a bit hacky (real hacky) but it would work. Use jQuery for ease of JS use after your include:

<script type="text/javascript" >
  $('#my_div').text('<?php echo $my_var ?>');
</script>

Upvotes: 0

Bjoern
Bjoern

Reputation: 16304

Three suggestions:

  1. Rearrange your HTML so that your button is below the declaration. Then use CSS to let your button appear above the div-container.
  2. Change your php scripts so the declaration is done somewhere else before your button.
  3. Use Jscript to change your button (p.e. like Amir Noori suggested).

Upvotes: 4

LindaJeanne
LindaJeanne

Reputation: 214

Is there any reason that you can't do the require before the button? If so, that's the real problem that you're trying to solve, because no, before you put the value in the variable, it isn't in the variable, and hence can't be echoed.

So to answer the question-behind-the-question, it's necessary to know more about what you're trying to do.

Upvotes: 0

user924016
user924016

Reputation:

No. You can not echo out something that is not declared.

Upvotes: 8

Soosh
Soosh

Reputation: 812

you can add the variable with javascript

<button>Button Name</button>
<div><?php require_once('your_file.php'); ?></div>
<script> $('#btnID').html('<?php $var ?>')</script>

note:I don't think it is possible to use a variable before declaring it. with my code you actually using it after declaring it.

Upvotes: 1

Related Questions