PHP Syntax
A PHP script can be inserted into the page at any point.
A PHP script begins with the character "?php" and concludes with the character"?>":
<?php
// PHP code goes here
?>
Note: A semicolon is used at the end of PHP statements (;).
PHP Case Sensitivity
Keywords (e.g., if, else, while, echo, etc.) are case-insensitive in PHP, as are classes, functions, and user-defined functions. All variable names, however, are case-sensitive!
All three echo statements in the example below are equal and legal:
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
If we look at the following example, only the first statement will display the value of the $color variable! This is because $name, $NAME, and $NaMe are treated as three different variables:
<!DOCTYPE html>
<html>
<body>
<?php
$name = "Priyanka";
echo "My name is " . $name. "<br>";
echo "My dog's name is " . $NAME. "<br>";
echo "My surname is " . $NaMe. "<br>";
?>
</body>
</html>
Comments in PHP
A line in PHP code that is not executed as part of the program is called a comment. Its sole purpose is for someone looking at the code to read it.
Comments can be used to:
- Make your code more understandable to others.
- Recall what you did - Most programmers have had the experience of returning to their work after a year or two and having to re-learn what they did. Comments can serve as a reminder of what you were thinking when you wrote the code.
PHP supports several ways of commenting:
The syntax for single-line comments:
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
?>
</body>
</html>
The syntax for multiple-line comments:
<!DOCTYPE html>
<html>
<body>
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body>
</html>
We can use comments to leave out parts of the code:
<!DOCTYPE html>
<html>
<body>
<?php
// We can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
Best Practices in PHP
If we want to be a professional developer, we must know, understand, and follow the language's best practices, and we should begin practising them as soon as we write our first line of code.
1.) Maintaining Proper Documentation of your Code
Maintaining adequate code documentation is more crucial than you may have realized. It not only aids others in understanding your code, but it also aids you in remembering what you've written when you go back to review it later.
As a result, using good comments to make your code understandable to everyone is always a smart practice.
2.) Maintaining a Proper Coding Standard
Maintaining a proper coding standard is essential, as it can become a painful problem if different programmers (working on the same project) start using different coding standards.
If everybody starts inventing their coding standards, the source code can become completely unmanageable. Some programmers don't try to follow any coding standards at all, and their code begins to resemble a large mound of junk and nothing more.
It will be easier for others to debug your code if you follow a decent coding standard, and your joint projects will be far more productive.
3.) Never Use Short Tags
Using "?" or "%" is never a good idea, and it doesn't make your code look any more professional.
This malpractice can cause problems with XML parsers and make your code incompatible with future versions of PHP.
4.) Use Meaningful Variable and Function Names in your Code
If you don't utilize a consistent naming convention and instead use generic and meaningless names everywhere.
Always attempt to name your variables and functions in a way that is meaningful and grammatically correct, and make it a habit to separate each word with underscores. Also, attempt to be consistent with the norm you're following so that others can immediately and readily comprehend your convention.
5.) Indentation, White Spacing and Line Length
We also need to consider indentation, white spaces, and line lengths specifically. We should strive to retain a four-space indent. Tab should never be used because different machines have different Tab settings. Also, keep the line length less than 80 characters to ensure that your code is easily readable to you and other developers.
The main idea is to make your code look clean, easily readable, and debuggable by you and other fellow programmers.
6.) Single Quotes vs. Double Quoted Strings
We need to understand the difference between the single-quoted strings and the double-quoted ones. If you have a simple string to display, always go for single quotes.
But if you have variables and special characters like "n," "t" in your string, you must use double quotes, which will get your line parsed by the PHP interpreter and take more execution time than single-quoted strings.
7.) Never Use Functions inside Loops
Often programmers tend to make the mistake of using functions inside of loops. It compromises performance in exchange for saving a line of code.
Bad Practice:
for ($i = 0, $i <= count($array); $i++)
{
//statements
}
You can also try this code with Online PHP Compiler
Run Code
Good Practice:
for ($i = 0; $i < $count; $i++)
{
//statements
}
You can also try this code with Online PHP Compiler
Run Code
If we take on the burden of storing the function's return value in a separate variable before the loop, we will save enough execution time since in the first scenario, the function will be called and executed every time the loop is encountered, which can raise the program's time complexity for big loops.
8.) Using Single Quotes around Array Indexes
$array['quotes'] and $array[quotes] are two different things, and we must be aware of them. Unquoted strings used as array indexes are treated as constants by PHP, and if the constant has never been defined before, it will be considered "self-defined" and a warning will be raised.
9.) Understanding Strings in a Better Way
In the following example and see which print statement is the fastest.
Code Snippet:
$a = ‘PHP’;
print “This a $a program.”;
echo “This a $a program.”;
echo “This a “.$a.” program.”;
echo “This a ”,$a,” program.”;
You can also try this code with Online PHP Compiler
Run Code
The last and the most uncommon statement is the fastest. Because the "print" statement is slower than the "echo" statement, the first one clearly loses. The third statement triumphs over the second because it employs concatenation rather than inline variables.
The last line, which is less well-known, wins since it contains no string operations and is simply a list of comma-separated strings.
10.) Turning on Error Reporting for Development Purposes
PHP has a beneficial function, error_reporting(), which can be used to spot various problems or errors in your PHP application during development.
There are often some errors, which will certainly not stop your entire application from working, but they are potential bugs that will reside in your code. We all want to write code error-free in every way.
Various error reporting levels are available in PHP, like E_NOTICE, E_PARSE, E_WARNING, etc., E ALL, on the other hand, can be used to report a wide range of faults. When you're finished developing your code, remember to turn off error reporting so that your visitors don't become spooked by numerous nonsensical warnings.
11.) Using the DRY Approach
DRY which stands for Don't Repeat Yourself is a programming principle in software engineering that aims to reduce redundancy in your code.
It's not only a PHP notion; it can be used for any programming language, including JAVA, C++, and others. An example code will greatly aid your understanding of the DRY technique.
$mysql = mysql_connect(‘localhost’, ‘admin’, ‘admin_pass’);
mysql_select_db(‘wordpress’ or die(‘Cannot Select Database.’);
You can also try this code with Online PHP Compiler
Run Code
The code will now look like this after applying the DRY approach:
$db_host = ‘localhost’;
$db_user = ‘admin’;
$db_pass = ‘admin_pass’;
$db_name = ‘wordpress’;
$mysql = mysql($db_host, $db_user, $db_pass);
mysql_select_db($db_name);
You can also try this code with Online PHP Compiler
Run Code
12.) Try to Prevent Deep Nesting
As far as possible, avoid deep nesting levels in your code. It can make it difficult for you to debug your code and frustrate individuals who are trying to review it.
To minimize unnecessary deep nesting, try to apply conditions as logically as feasible. It's a bad programming approach that can make your code look unattractive to your coworkers.
Must Read PHP Projects With Source Code
FAQs
-
Who is the father of PHP and explain the changes in PHP versions?
Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3nis the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current generation of PHP, which uses the Zend engine under the hood. PHP 5 uses Zend engine 2 which, among other things, offers many additional OOP features.
-
Which programming language does PHP resemble?
PHP syntax resembles Perl and C.
-
How do you execute a PHP script from the command line?
use the PHP command-line interface (CLI) and specify the file name of the script to be executed as follows:
php script.php
Key Takeaways
PHP that stands for "PHP: Hypertext Preprocessor," is an HTML-enabled server-side programming language.
For PHP, ".php" is the default file extension. A PHP script can be inserted into the page at any point. A PHP script begins with the character "?php" and concludes with the character "?>".
For more PHP blogs kindly visit the following links:
- PHP Intro
- PHP Form Handling
Happy learning!