PHP Syntax

PHP Syntax: A Comprehensive Guide with Examples

PHP Syntax

PHP (Hypertext Preprocessor) is a widely used server-side scripting language designed for web development. Understanding PHP syntax is essential for writing clean, efficient, and functional code. In this guide, we’ll cover all the key aspects of PHP syntax with practical examples.

1. Basic PHP Syntax Structure

A PHP script starts with <?php and ends with ?>. All PHP code must be enclosed within these tags.

Example:

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

Key Points:

  1. PHP statements end with a semicolon (;).
  2. The echo statement outputs text.
  3. Comments can be single-line (// or #) or multi-line (/* ... */).

2. Variables in PHP

Variables in PHP start with a dollar sign ($) followed by the variable name.

Example:

<?php  
    $name = "John Doe";  
    $age = 25;  
    echo "Name: $name, Age: $age";  
?>  

Rules for PHP Variables:

  1. Must start with $ followed by a letter or underscore.
  2. Case-sensitive ($var ≠ $Var).
  3. No need to declare data types explicitly.

3. Data Types in PHP

PHP supports several data types:

Data TypeExample
String$text = "Hello";
Integer$num = 10;
Float$price = 9.99;
Boolean$isTrue = true;
Array$colors = ["Red", "Green"];
NULL$var = null;

Example:

<?php  
    $name = "Alice";      // String  
    $score = 95;          // Integer  
    $average = 85.5;      // Float  
    $isPassed = true;     // Boolean  
    $subjects = ["Math", "Science"]; // Array  
?>  

4. Operators in PHP

PHP includes various operators:

Arithmetic Operators

<?php  
    $a = 10;  
    $b = 5;  
    echo $a + $b;  // 15  
    echo $a - $b;  // 5  
    echo $a * $b;  // 50  
    echo $a / $b;  // 2  
    echo $a % $b;  // 0  
?>  

Comparison Operators

<?php  
    $x = 10;  
    $y = "10";  
    var_dump($x == $y);   // true (value match)  
    var_dump($x === $y);  // false (strict type check)  
?>  

Logical Operators

<?php  
    $a = true;  
    $b = false;  
    var_dump($a && $b);  // false (AND)  
    var_dump($a || $b);  // true (OR)  
    var_dump(!$a);       // false (NOT)  
?>  

5. Conditional Statements

PHP supports ifelseelseif, and switch for decision-making.

Example (if-else):

<?php  
    $marks = 75;  
    if ($marks >= 60) {  
        echo "Passed!";  
    } else {  
        echo "Failed!";  
    }  
?>  

Example (switch):

<?php  
    $day = "Monday";  
    switch ($day) {  
        case "Monday":  
            echo "Start of the week!";  
            break;  
        default:  
            echo "Another day";  
    }  
?>  

6. Loops in PHP

PHP supports forwhiledo-while, and foreach loops.

Example (for loop):

<?php  
    for ($i = 1; $i <= 5; $i++) {  
        echo "Number: $i <br>";  
    }  
?>  

Example (foreach loop for arrays):

<?php  
    $colors = ["Red", "Green", "Blue"];  
    foreach ($colors as $color) {  
        echo "$color <br>";  
    }  
?>  

7. Functions in PHP

Functions are reusable blocks of code

Example:

<?php  
    function greet($name) {  
        return "Hello, $name!";  
    }  
    echo greet("John");  // Output: Hello, John!  
?>  

Key Points:

  1. Functions can accept parameters.
  2. Use return to send back a value.

8. Arrays in PHP

Arrays store multiple values in a single variable.

Indexed Array:

<?php  
    $fruits = ["Apple", "Banana", "Orange"];  
    echo $fruits[0];  // Apple  
?>  

Associative Array:

<?php  
    $person = ["name" => "John", "age" => 30];  
    echo $person["name"];  // John  
?>  

9. Superglobal Variables

PHP has predefined global variables like $_GET$_POST$_SESSION, etc.

Example (Using $_GET):

<?php  
    // URL: example.com?name=John  
    echo "Hello, " . $_GET['name'];  
?>  

10. Error Handling

Use try-catch for exception handling.

Example:

<?php  
    try {  
        $result = 10 / 0;  
    } catch (Exception $e) {  
        echo "Error: " . $e->getMessage();  
    }  
?>  

Conclusion

Understanding PHP syntax is crucial for web development. This guide covered variables, data types, operators, loops, functions, arrays, and error handling.

By mastering these concepts, you can write efficient PHP scripts for dynamic web applications.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *