There are a few standards for your code, that will make bugs less frequent, and debugging easier. You will be marked down if you don't follow these rules.
Indenting
This is the most important standard: all code blocks must be indented.
Code in if
s and loops must be indented, by 2 or 4 spaces. Either is fine. You must be consistent within each file, though.
Examples:
- // Is there input?
- if (!isset($_GET['state'])) {
- $errorMessage = 'Sorry, you must give a state.';
- }
- if ($errorMessage == '') {
- // OK so far.
- $stateShortName = strtoupper(trim($_GET['state']));
- // Is the state known?
- if ($stateShortName != 'MI' && $stateShortName != 'IL') {
- $errorMessage = "Sorry, '$stateShortName' is not a recognized state.";
- }
- }
- else {
- print "<p>W00t!</p>\n";
- }
- <?php
- if ($errorMessage != '') {
- print "<p class='alert-danger text-danger m-2 p-2'>$errorMessage</p>";
- }
- else {
- // There are doggos to show.
- print "<p>Doggos in the $householdName household.</p>\n";
- print "<ul>\n";
- foreach ($rows as $row) {
- $doggoName = $row['doggo_name'];
- print "<li>$doggoName</li>\n";
- }
- print "</ul>\n";
- }
- ?>
Indent CSS like this:
- .error-message {
- color: red;
- font-weight: bold;
- border: red solid thin;
- padding: 1rem;
- }
Indent HTML like this:
- <!doctype html>
- <html lang="en">
- <head>
- <title>Title</title>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
- </head>
- <body>
- <h1>Doggos</h1>
- <p>Doggos rule!</p>
- <div class="box">
- <p>That's so.</p>
- <p>They do, in fact, <span class="true">rule</span>.</p>
- </div>
- </body>
- </html>
span
s don't need to be indented, since they're inline tags.
Variable names
Use camel case for variable names. All characters lowercase, except when you have a multi-word name. Make the first character of the second and subsequent words uppercase. Examples:
- $dogCount
- $averageAcidity
- $monthlyPayment
Use variable names that makes sense in the problem domain. E.g., $monthlyPayment
, not $x33
.
Start boolean variable names with is
, or has
. Examples:
- $isDataOk = true;
- $hasExploded = false;
PHPDocs for functions
Add PHPDocs to functions. For example:
- /**
- * Get a value for parameter in the GET array.
- * @param string $paramName Name of the parameter.
- * @return string|null Value, or null if not found.
- */
- function getParamFromGet(string $paramName) {
- $returnValue = null;
- if (isset($_GET[$paramName])) {
- $returnValue = $_GET[$paramName];
- if ($returnValue == '') {
- $returnValue = null;
- }
- }
- return $returnValue;
- }
Document the purpose of the function, its parameters, and its return value.
Braces
Don't omit braces from if
s or loops. Not this:
- if ($hasExploded)
- print "Boom!";
- else
- print "Nothing happened.";
Instead:
- if ($hasExploded) {
- print "Boom!";
- }
- else {
- print "Nothing happened.";
- }