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:
$variableName = value;
Example:
$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:
$2name = "Wrong";
$user-name = "Wrong";
Example: Using Variables
<?php
$user = "Jay";
$score = 92;
echo "Welcome, $user!<br>";
echo "Your score is $score.";
?>
Output:
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:
define("SITE_NAME", "ScriptBuzz");
Example:
<?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.
Type | Description | Example |
---|---|---|
String | Sequence of characters | "Hello" |
Integer | Whole number | 100 |
Float | Decimal number | 3.14 |
Boolean | true or false | true |
Array | Collection of values | ["PHP", "JS"] |
Null | Empty or no value | null |
Example: Using All Data Types
<?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:
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:
$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:
- Create a file called
profile.php
- Declare these variables:
$name = "Alice"
$age = 28
$isMember = true
$skills = ["HTML", "CSS", "PHP"]
- Use
echo
to display this sentence:
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
π‘ Explore More PHP Learning Tools & Resources
PHP Practice Quiz
Test your PHP skills with real coding questions and scoring.
PHP Interview Questions
Prepare for interviews with common PHP questions and answers.
Educational AI Tutor
Ask PHP questions and get instant AI-powered explanations.
Question Generator
Auto-generate PHP interview questions for quick practice.