Basics of PHP syntax

To write PHP code in an HTML file, you can use the PHP opening and closing tags <?php and ?>. Any code written inside these tags will be processed by the PHP engine. Here's an example:

<!DOCTYPE html>
<html>
  <head>
    <title>PHP Example</title>
  </head>
  <body>
    <?php
      // PHP code goes here
      echo "Hello, World!";
    ?>
  </body>
</html>

To write code on a PHP file, you simply need to save your code in a file with the extension .php. Here's an example:

<?php
  // PHP code goes here
  echo "Hello, World!";
?>

You can then run this PHP file on a web server that has PHP installed, and it will process the PHP code and display the output in the web browser.

Now, let's start with the basics of PHP syntax!

  1. Comments In PHP, you can use comments to add notes to your code. Comments start with // for single-line comments or /* and end with */ for multi-line comments. For example:

// This is a single-line comment

/*
This is a
multi-line
comment
*/
  1. Variables Variables are used to store data in PHP. To create a variable, you use the $ symbol followed by the variable name. For example:

$name = "John";
$age = 25;
$height = 1.75;
  1. Data Types PHP has several data types, including strings, integers, floats, booleans, arrays, and objects. Here are some examples:

// String
$name = "John";

// Integer
$age = 25;

// Float
$height = 1.75;

// Boolean
$isStudent = true;

// Array
$fruits = array("apple", "banana", "orange");

// Object
class Person {
  public $name;
  public $age;
}

$person = new Person();
$person->name = "John";
$person->age = 25;
  1. Output You can output data in PHP using the echo statement. For example:

$name = "John";
echo "Hello, " . $name; // Output: Hello, John
  1. Control Structures PHP has several control structures, including if-else statements, while loops, for loops, and switch statements. Here are some examples:

// If-else statement
$age = 25;
if ($age >= 18) {
  echo "You are an adult";
} else {
  echo "You are not an adult";
}

// While loop
$i = 0;
while ($i < 10) {
  echo $i;
  $i++;
}

// For loop
for ($i = 0; $i < 10; $i++) {
  echo $i;
}

// Switch statement
$fruit = "apple";
switch ($fruit) {
  case "apple":
    echo "This is an apple";
    break;
  case "banana":
    echo "This is a banana";
    break;
  default:
    echo "This is not an apple or a banana";
}

These are just the basics of PHP syntax, but they should help you get started. Good luck!

Last updated