Understanding PHP Variables, Constants, and Operators

PHP Variables

Variables are containers for storing data values. They are declared with a dollar sign ($) followed by the variable name.

Rules for naming variables:

  • Must start with a letter or underscore
  • Can contain letters, numbers, and underscores
  • Are case-sensitive

Example:

$name = "Alice";
$age = 30;
$is_student = true;
PHP

PHP Constants

Constants are similar to variables but their values cannot be changed once defined. They are typically used for values that remain constant throughout the script.

Define a constant:

define("PI", 3.14159);
PHP

Access a constant:

echo PI; // Output: 3.14159
PHP

PHP Operators

Operators are symbols used to perform operations on variables and values.

Arithmetic operators:

  • + Addition
  • - Subtraction
  • * Multiplication
  • / Division
  • % Modulus (remainder)
  • ** Exponentiation

Example:

$x = 10;
$y = 5;
$sum = $x + $y;
$difference = $x - $y;
$product = $x * $y;
$quotient = $x / $y;
$remainder = $x % $y;
$power = $x ** 2;
PHP

Assignment operators:

  • = Assign a value to a variable
  • += Add and assign
  • -= Subtract and assign
  • *= Multiply and assign
  • /= Divide and assign
  • %= Modulus and assign

Comparison operators:

  • == Equal to
  • != Not equal to
  • < Less than
  • > Greater than
  • <= Less than or equal to
  • >= Greater than or equal to

Logical operators:

  • && And
  • || Or
  • ! Not

Example:

$a = 5;
$b = 10;
if ($a < $b && $b > 0) {
    echo "a is less than b and b is positive";
}
PHP

Understanding variables, constants, and operators is crucial for building dynamic PHP applications. In the next article, we’ll explore control flow statements.

Leave a Reply