PHP Basics

Section 1: PHP Basics

In this section, we'll cover the fundamental building blocks of PHP, including variables and data types, operators and expressions, as well as control flow statements.


Variables and Data Types

Declaring Variables in PHP:

In PHP, variables are declared using the $ symbol followed by the variable name. Variable names are case-sensitive.

<?php

    $name = "John";   // String

    $age = 25;        // Integer

    $height = 5.9;     // Float

    $isStudent = true; // Boolean

?>


Understanding Data Types:

Strings:

Represented by sequences of characters.

Enclosed in single (') or double (") quotes.


<?php

    $name = "Alice";

?>

Numbers:

Integers or floats for numeric values.

<?php

    $age = 30;       // Integer

    $height = 6.1;   // Float

?>

Booleans:

Represents true or false.

<?php

    $isStudent = true;

?>


Operators and Expressions

Arithmetic Operators:

<?php

    $num1 = 10;

    $num2 = 5;


    $sum = $num1 + $num2; // Addition

    $difference = $num1 - $num2; // Subtraction

    $product = $num1 * $num2; // Multiplication

    $quotient = $num1 / $num2; // Division

    $remainder = $num1 % $num2; // Modulus (Remainder)

?>

Comparison Operators:

<?php

    $a = 10;

    $b = 5;


    $isEqual = ($a == $b); // Equal

    $isNotEqual = ($a != $b); // Not Equal

    $isGreaterThan = ($a > $b); // Greater Than

    $isLessThan = ($a < $b); // Less Than

?>

Logical Operators:

<?php

    $x = true;

    $y = false;


    $andResult = ($x && $y); // Logical AND

    $orResult = ($x || $y);  // Logical OR

    $notResult = !$x;        // Logical NOT

?>


Control Flow Statements

If, Else If, Else Statements:

<?php

    $grade = 75;


    if ($grade >= 90) {

        echo "A";

    } elseif ($grade >= 80) {

        echo "B";

    } elseif ($grade >= 70) {

        echo "C";

    } else {

        echo "F";

    }

?>

Switch Statement:

<?php

    $day = "Monday";


    switch ($day) {

        case "Monday":

            echo "It's the start of the week.";

            break;

        case "Friday":

            echo "It's almost the weekend.";

            break;

        default:

            echo "It's a regular day.";

    }

?>

By mastering these PHP basics, you'll be well-equipped to handle variables, data types, operators, and control flow in your PHP scripts. Continue practicing and applying these concepts as you progress in your PHP development journey.