One technique is to default the value to NULL
:
$var = NULL;
if (isset($_GET['var'])) {
$var = $_GET['var'];
} ?>
Then when setting the attribute on the tag, isset()
doesn't need to be used.
<body class="whatever" <?php if($var) {echo "id=\"$var\""; } ?>>
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
var
I would suggest using the ternary option which makes it a lot cleaner and easier to understand.$var = $GET['var'] ?? null;
See Comparison Operators for more details. \$\endgroup\$$var = $_GET['var']; } else { $var = NULL;
in the head? As for why an ID on the body, long story, but adding a class to the body is not an option and I need to hide certain content depending on which app is loading the webpage. \$\endgroup\$