Variables, Constants & Data Types in PHP

What is a Variable?

A variable in PHP is a named container used to store data that can change during the execution of a script. Variables are fundamental to all programming languages β€” and in PHP, they are especially flexible and easy to work with.

In PHP:

The assignment operator = assigns a value to the variable.

Every variable must begin with a dollar sign ($).

Syntax:

PHP
$variableName = value;

Example:

PHP
$name = "ScriptBuzz";
$age = 25;

Rules for Variable Names

  • Must begin with a $ followed by a letter or underscore
  • Can only contain letters, numbers, and underscores
  • Case-sensitive ($name and $Name are different)
  • Cannot contain spaces or special characters

Invalid:

PHP
$2name = "Wrong";
$user-name = "Wrong";

Example: Using Variables

PHP
<?php
  $user = "Jay";
  $score = 92;

  echo "Welcome, $user!<br>";
  echo "Your score is $score.";
?>

Output:

LESS
Welcome, Jay!
Your score is 92.

What is a Constant?

A constant is a name for a value that cannot be changed once defined.

While variables are meant to change, constants in PHP are values that remain fixed throughout the execution of the script.

Why Use Constants?

  • For configuration settings like site name, database credentials, API keys, etc.
  • They improve code readability and reduce accidental overwrites.

Syntax:

PHP
define("SITE_NAME", "ScriptBuzz");

Example:

PHP
<?php
  define("PI", 3.14);
  echo "Value of PI is " . PI;
?>

πŸ’‘ Use constants for values that should not change (e.g., API keys, site titles, limits).

PHP Data Types

PHP is a loosely typed language, meaning you don’t have to explicitly declare data types β€” PHP assigns types automatically based on the assigned value.

TypeDescriptionExample
StringSequence of characters"Hello"
IntegerWhole number100
FloatDecimal number3.14
Booleantrue or falsetrue
ArrayCollection of values["PHP", "JS"]
NullEmpty or no valuenull

Example: Using All Data Types

PHP
<?php
$name = "ScriptBuzz";      // String
$visitors = 1000;          // Integer
$conversionRate = 2.5;     // Float
$isActive = true;          // Boolean
$topics = ["PHP", "MySQL", "JavaScript"]; // Array
$admin = null;             // Null

echo "Welcome to $name!<br>";
echo "Visitors: $visitors<br>";
echo "Conversion Rate: $conversionRate%<br>";
echo "Active: " . ($isActive ? "Yes" : "No") . "<br>";
echo "Topics: " . implode(", ", $topics) . "<br>";
echo "Admin: " . ($admin ?? "None");
?>

Output:

YAML
Welcome to ScriptBuzz!
Visitors: 1000
Conversion Rate: 2.5%
Active: Yes
Topics: PHP, MySQL, JavaScript
Admin: None

Type Casting (Optional)

PHP automatically converts between types, but you can force conversion:

PHP
$score = "90";         // String
$score = (int)$score;  // Cast to integer

βœ”οΈ Type casting is useful in strict comparisons or mathematical operations.

Best Practices for PHP Variables & Constants

  • Use camelCase or snake_case consistently ($userName, $user_name)
  • Constants should use uppercase with underscores (MAX_USERS)
  • Always initialize variables before use
  • Use meaningful names that describe the purpose ($discountRate, not $dr)
  • Avoid reusing variable names unless intentional
  • Avoid magic numbers β€” use constants for fixed values

Notes:

  • PHP variables start with $ and are case-sensitive
  • Constants are declared with define() and cannot change
  • PHP supports string, int, float, bool, array, and null
  • Use arrays to group multiple values
  • PHP automatically converts types, but casting is possible

Common Mistakes to Avoid

  • ❌ Using $ in constant names (constants do NOT start with $)
  • ❌ Using hyphens or special symbols in variable names
  • ❌ Forgetting semicolons ; at the end of a statement
  • ❌ Mixing data types carelessly in operations

Practice Challenge

βœ… Try this on your own:

  1. Create a file called profile.php
  2. Declare these variables:
    • $name = "Alice"
    • $age = 28
    • $isMember = true
    • $skills = ["HTML", "CSS", "PHP"]
  3. Use echo to display this sentence:
PLSQL
Alice is 28 years old. Membership: Yes. Skills: HTML, CSS, PHP

4. Use a constant for SITE_NAME and show it at the top.

Practice Tasks

βœ… Task 1: Variable Playground
Create a PHP file named profile.php. Inside:

  • Define $name = "Emma", $age = 30, $skills = ["PHP", "CSS"], $isLoggedIn = true
  • Display:
    Emma is 30 years old. Skills: PHP, CSS. Logged In: Yes

βœ… Task 2: Define Constant
Define a constant called SITE_NAME with value "ScriptBuzz.com"
Display it using echo.

βœ… Task 3: Type Conversion

  • Set $x = "50"
  • Convert it to an integer
  • Multiply by 2 and print the result