PHP Syntax
When you're writing PHP, you're essentially writing instructions for the server to process and return plain HTML to the user. A PHP script begins with <?php and ends with ?>. Any PHP code you want to run should be placed between these tags. For convenience, PHP files usually end with the .php extension.
To give you an idea, here’s a small example of a PHP file:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
In this example, PHP is used to echo “Hello World!” into the webpage. Notice how PHP statements end with a semicolon.
PHP is quite flexible when it comes to case sensitivity. For instance, PHP keywords like echo can be written in any form, such as echo, ECHO, or EcHo. However, variable names are case-sensitive, which means $color, $COLOR, and $coLOR would be considered different variables.
Here's a quick example to show how flexible PHP can be with embedding in HTML:
<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'This part is processed by PHP.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
In practice, you might prefer to omit the closing PHP tag (?>) at the end of files entirely if it’s purely PHP code. This can help avoid accidentally outputting new lines or spaces that could cause issues, especially when using PHP for larger projects.
One last handy tip: PHP provides a shorthand for echo using the <?= ?> tags for quick output, like so:
<?= "Quick output for PHP!" ?>
Just remember that PHP is organized and controlled by using semicolons to end instructions, much like writing a sentence.
That's a wrap on the basics of PHP syntax! You’ll find that mixing PHP with HTML allows you to create dynamic web content easily. If you have more questions, feel free to ask here!