0

I have something like this:

PHP code at the start:

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

Then HTML code:

 <html>
 <head>
 <title>Title</title>
 </head>
 <body>

Then again PHP:

 <?php
 // code comes here, and I want to access variable $variable here.
 ?>

And then HTML code ends:

 </body>
 </html>

Is it possible to do this somehow? I don't want to create another file; I need to do this in this file.

1
  • How about, try it and see? Yes, it'll work. Commented Jan 20, 2014 at 12:03

4 Answers 4

4

Not Required unless if you are accessing it under functions ( as it will lose their scope)

test1.php

<?php
$var = 1;


//.. your code...
?>

<html>.....

<?php
echo $var; // prints 1

whereas the below code won't work...

<?php
$var = 1;

function displayVar()
{
echo $var; // You will get a notice .. ! 
}
Sign up to request clarification or add additional context in comments.

Comments

2

Just do what you stated above and it will work.

<?php
$variable = 'Hello';
?>
<html>
<head>
</head>
<body>
<?php echo $variable; ?>
</body>
</html>

The above example will display a simple webpage with 'Hello' as the content. This is one of best strength of PHP actually.

Comments

1

try this

echo ($variable);

or

print($variable);

Comments

-1

If it is the same file, yes it is possible, unless the variable is in a function. But this is a very simple question, that you could have tested yourself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.