Variables, Data Types, and Operators

Now that you’ve set up your PHP development environment, it’s time to dive into the basics of PHP programming. In this lesson, we’ll cover variables, data types, and operators, which are fundamental building blocks for writing PHP code.


In PHP, variables are used to store data that can be used and manipulated later in your code. Variables in PHP start with a dollar sign ($) followed by the variable name. Variable names are case-sensitive and must start with a letter or an underscore.

To assign a value to a variable, use the equal sign (=):

$name = "John Doe";
$age = 30;
$score = 85.5;

Data Types

PHP supports several data types:

String: A sequence of characters, used to store text. Strings can be enclosed in single or double quotes.

$string1 = 'Hello, World!';
$string2 = "Hello, World!";

Integer: A whole number without a decimal point, used to store numeric values.

$int1 = 42;
$int2 = -10;

Float (or double): A number with a decimal point, used to store decimal values.

$float1 = 3.14;
$float2 = -0.5;

Boolean: Represents either true or false.

$bool1 = true;
$bool2 = false;

Array: An ordered collection of values, which can be of any data type.

$array1 = array(1, 2, 3, 4, 5);
$array2 = array("apple", "banana", "cherry");

Object: An instance of a class, used to represent complex data structures and behaviors.

class Person {
  public $name;
  public $age;

$person = new Person();
$person->name = "John Doe";
$person->age = 30;

NULL: Represents a variable with no value.

$nullVar = NULL;


PHP provides a wide range of operators to perform various operations on variables:

Arithmetic operators: Perform basic mathematical operations.

$sum = 10 + 20;
$difference = 30 - 10;
$product = 5 * 6;
$quotient = 24 / 8;
$remainder = 10 % 3;

Assignment operators: Assign a value to a variable.

$x = 10;
$x += 5; // Same as $x = $x + 5;
$x -= 3; // Same as $x = $x - 3;

Comparison operators: Compare the values of two variables.

$a == $b; // Equal
$a != $b; // Not equal
$a < $b; // Less than
$a > $b; // Greater than

Logical operators: Perform logical operations (AND, OR, NOT).

$result = $a && $b; // AND
$result = $a || $b; // OR
$result = !$a; // NOT

Actionable Work

To practice using variables, data types, and operators, try the following exercises:

  1. Create a PHP script that calculates the area of a rectangle with given width and height.
  2. Create a PHP script that calculates the sum of all integers between 1 and 100.
  3. Create a PHP script that checks if a given number is even or odd