PHP Syntax

PHP (Hypertext Preprocessor) is a server-side scripting language used for web development. Here are some basic PHP syntax rules:


1. Opening and Closing Tags: PHP code is embedded within HTML using opening and closing PHP tags.

php
<?php
// PHP code here
?>

2. Comments: PHP supports single-line and multi-line comments.

php
// This is a single-line comment

/*
This is a multi-line
comment
*/

3. Variables: PHP variables start with the dollar sign `$`, followed by the variable name. Variable names are case-sensitive and can contain letters, numbers, and underscores. They must start with a letter or underscore.

php
$name = "John";
$age = 30;

4. Data Types: PHP supports various data types, including strings, integers, floats, booleans, arrays, objects, and more.

php
$name = "John"; // String
$age = 30; // Integer
$height = 5.10; // Float
$isStudent = true; // Boolean
$colors = array("red", "green", "blue"); // Array

5. Print and Echo: PHP can output content using `echo` or `print`.

php
$name = "John";
echo "Hello, " . $name; // Output: Hello, John
print "Hello, $name"; // Output: Hello, John

6. String Concatenation: Use the dot (`.`) to concatenate strings.

php
$first_name = "John";
$last_name = "Doe";
$full_name = $first_name . " " . $last_name; // Output: John Doe

7. Conditional Statements: PHP supports standard conditional statements like `if`, `else`, and `elseif`.

php
$age = 25;

if ($age < 18) {
    echo "You are a minor.";
} elseif ($age >= 18 && $age < 65) {
    echo "You are an adult.";
} else {
    echo "You are a senior.";
}

8. Loops: PHP provides different types of loops, including `for`, `while`, `do-while`, and `foreach`.

php
// For loop
for ($i = 0; $i < 5; $i++) {
    echo $i; // Output: 01234
}

// While loop
$num = 1;
while ($num <= 5) {
    echo $num; // Output: 12345
    $num++;
}

// Foreach loop (for arrays)
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
    echo $color . " "; // Output: red green blue
}

9. Functions: Functions in PHP are defined using the `function` keyword.

php
function greet($name) {
    echo "Hello, " . $name;
}

greet("John"); // Output: Hello, John

10. Include and Require: PHP can include files using `include` or `require`.

php
include "header.php"; // Includes the content of header.php
require "footer.php"; // Requires the content of footer.php (fatal error if not found)

These are some of the fundamental PHP syntax rules. PHP is a versatile language with a wide range of features and functions that make it suitable for various web development tasks.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext