Adding ID to body tag from variable defined in URL I have written a small PHP script to get a variable from the URL and echo it in the body ID.

An example of the url:

http://www.example.com/?var=123


I have added this to the head of my HTML page:

&lt;?php if (isset($_GET['var'])) {
    $var = $_GET['var'];
} else {
    $var = NULL;
} ?&gt;


The body tag of the HTML page looks like this:

&lt;body class="whatever" &lt;?php if(isset($var)) {echo "id=\"$var\""; } ?&gt;&gt;


The result is a body tag like this when the ?var=123 is added to the URL:

&lt;body class="whatever" id="123"&gt;


This is working but I am sure there is a better way to go about it.
One technique is to default the value to NULL:

$var = NULL;
if (isset($_GET['var'])) {
    $var = $_GET['var'];
} ?&gt;


Then when setting the attribute on the tag, isset() doesn't need to be used.

&lt;body class="whatever" &lt;?php if($var) {echo "id=\"$var\""; } ?&gt;&gt;


For a demonstration of this, see this phpFiddle.

Note that it is recommended that PHP not be mixed in with HTML code. For a good explanation, refer to this answer to Should I Include PHP code in HTML or HTML in PHP? on the Software Engineering site. 


  Mixing languages is not a good idea. You don't put JavaScript in HTML, or HTML in JavaScript, or JavaScript in PHP, or HTML in Python or Ruby in SQL.1


As is recommended by that post, consider the use of templates:


  What are you probably looking for is called templates. Depending on the framework you use, it may already be available, usually under a form of MVC, where the template is in the view, or you may have to use a third-party template engine, such as Smarty.
  
  In both cases, the idea remains the same. You have PHP code strictly separated from the template which contains the HTML and a bit of very simplistic logic: simple loops over entities, conditions for conditional displaying of information, etc. When the PHP code is ready, it calls the template engine, passing to it some information. The engine uses a specific template to build the final output (often HTML, but other formats are possible as well) which is then sent to the user.1


1https://softwareengineering.stackexchange.com/a/291839/244085