Working with Variables, Data Types, and Operators in PHP

PHP is a versatile scripting language widely used for web development. Understanding how to work with variables, data types, and operators is fundamental to writing PHP scripts effectively. Let's delve into each aspect:

1. Variables in PHP:

Variables in PHP are used to store data values. They are declared using the $ symbol followed by the variable name. PHP variables are case-sensitive and must start with a letter or an underscore.

Example:

<?php
$name = "John";
$age = 30;
?>

2. Data Types in PHP:

PHP supports various data types, including:

  • String: A sequence of characters enclosed within quotes.
  • Integer: A whole number without decimals.
  • Float: A number with a decimal point or an exponent.
  • Boolean: Represents true or false values.
  • Array: A collection of key-value pairs.
  • Object: Instances of user-defined classes.
  • NULL: Represents a null value.
  • Resource: Special variables holding references to external resources.

Example:

<?php
$name = "John"; // String
$age = 30; // Integer
$height = 6.1; // Float
$isStudent = true; // Boolean
$grades = array(80, 85, 90); // Array
?>
 

3. Operators in PHP:

PHP supports various operators for performing operations on variables and values. These include:

  • Arithmetic Operators: Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulus (%), Increment (++), Decrement (--).
  • Assignment Operators: Assigns a value to a variable (e.g., =, +=, -=, *=, /=).
  • Comparison Operators: Compares values (e.g., ==, !=, <, >, <=, >=).
  • Logical Operators: Performs logical operations (e.g., &&, ||, !).
  • String Operators: Concatenates strings (e.g., .).
  • Array Operators: Concatenates arrays (e.g., +).

Example:

<?php
$x = 10;
$y = 5;

// Arithmetic operators
$sum = $x + $y; // 15
$difference = $x - $y; // 5
$product = $x * $y; // 50
$quotient = $x / $y; // 2
$remainder = $x % $y; // 0

// Assignment operators
$x += 5; // $x is now 15
$y -= 2; // $y is now 3

// Comparison operators
$is_equal = ($x == $y); // false
$is_greater = ($x > $y); // true

// Logical operators
$is_true = ($x > 0 && $y > 0); // true
$is_false = ($x < 0 || $y < 0); // false

// String operators
$name = "John";
$greeting = "Hello, " . $name; // "Hello, John"

// Array operators
$grades1 = array(80, 85);
$grades2 = array(90, 95);
$combined_grades = $grades1 + $grades2; // [80, 85, 90, 95]
?>



Practice Excercise Practice now