PHP Program to Demonstrate Variables and Types
Learn PHP step by step.
All about PHP - Variables and Types
Jan 29, 2026
## Chapter 6: Variables and Types
**Think of variables as labeled boxes where you store different things - like organizing your room!**
**Goal:** Learn to store values safely, understand what type you're holding, and avoid confusing type bugs.
### What is a Variable? - Your Personal Storage Box
**A variable is like a labeled box where you keep things. The label is the name, and what's inside is the value!**
```php
<?php
// Think of these as labeled boxes:
$name = "Aman"; // Box labeled "name" contains "Aman"
$age = 20; // Box labeled "age" contains 20
$price = 99.50; // Box labeled "price" contains 99.50
$isActive = true; // Box labeled "isActive" contains true/false
$nothing = null; // Box labeled "nothing" is empty!
```
**Visual Diagram: Variables as Storage Boxes**
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PHP Variable Boxes β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββββ ββββββββββββββββ βββββββββββββββββ
β β $name β β $age β β $price ββ
β β β β β β ββ
β β βββββββββββ β β βββββββββββ β β βββββββββββ ββ
β β β "Aman" β β β β 20 β β β β 99.50 β ββ
β β βββββββββββ β β βββββββββββ β β βββββββββββ ββ
β β β β β β ββ
β ββββββββββββββββ ββββββββββββββββ βββββββββββββββββ
β β
β ββββββββββββββββ ββββββββββββββββ β
β β $isActive β β $nothing β β
β β β β β β
β β βββββββββββ β β βββββββββββ β β
β β β true β β β β NULL β β β
β β βββββββββββ β β βββββββββββ β β
β β β β β β
β ββββββββββββββββ ββββββββββββββββ β
β β
β **Each box can only hold one thing at a time!** β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### PHP Variable Rules - The Labeling System
**PHP has simple rules for naming your boxes:**
```php
<?php
// These are correct:
$name = "John"; // Starts with letter
$_score = 100; // Starts with underscore
$user123 = "Alice"; // Contains numbers (but doesn't start with them)
// These will break:
$123name = "Bob"; // Cannot start with number
$user-name = "Mary"; // Cannot use hyphens
$my variable = "Tom"; // Cannot use spaces
```
**Memory Tip:** Think "Dollar sign first, then letter or underscore, then anything goes!"
### PHP Data Types - Different Kinds of Boxes
**PHP automatically knows what type of box you need based on what you put inside!**
```php
<?php
// String Box - holds text (words, sentences)
$message = "Hello World!";
$name = 'PHP is awesome!';
// Integer Box - holds whole numbers (no decimals)
$age = 25;
$year = 2024;
$count = -10;
// Float Box - holds decimal numbers
$price = 19.99;
$temperature = 98.6;
$pi = 3.14159;
// Boolean Box - holds true/false (yes/no)
$isLoggedIn = true;
$hasPermission = false;
$isStudent = true;
// Null Box - holds nothing (empty box)
$middleName = null;
$data = NULL;
// Array Box - holds multiple items (like a storage container)
$colors = ["red", "green", "blue"];
$scores = [95, 87, 92, 88];
```
### Visual Type Examples - Real Life Scenarios
```php
<?php
// Shopping Cart Example
$productName = "Wireless Mouse"; // String - product name
$price = 29.99; // Float - price with cents
$quantity = 2; // Integer - whole items
$inStock = true; // Boolean - available or not
$discount = null; // Null - no discount applied
$features = ["wireless", "USB", "ergonomic"]; // Array - multiple features
// User Profile Example
$username = "john_doe"; // String - username
$age = 28; // Integer - age in years
$height = 5.9; // Float - height in feet
$isVerified = true; // Boolean - account verified
$bio = null; // Null - no bio written yet
$hobbies = ["reading", "coding", "gaming"]; // Array - multiple hobbies
```
### Checking What's Inside Your Boxes
**Use `var_dump()` to peek inside your boxes and see what type they are:**
```php
<?php
$test1 = "Hello";
$test2 = 42;
$test3 = 3.14;
$test4 = true;
$test5 = null;
echo "Let's check what's inside each box:n";
var_dump($test1); // string(5) "Hello"
var_dump($test2); // int(42)
var_dump($test3); // float(3.14)
var_dump($test4); // bool(true)
var_dump($test5); // NULL
```
### Type Conversion - When PHP Changes Your Box
**Sometimes PHP automatically changes your box type when needed:**
```php
<?php
// PHP is helpful - it converts types when it makes sense!
$number = 42; // Integer box
$text = "The answer is " . $number; // PHP converts 42 to "42"
echo $text; // Output: "The answer is 42"
$price = "19.99"; // String box with number
$tax = $price * 0.08; // PHP converts "19.99" to 19.99 for math!
echo $tax; // Output: 1.5992
```
### Common Variable Mistakes (And How to Fix Them!)
| Mistake | What Happens | Fix It Like This |
|---------|-------------|------------------|
| **Forgetting the $ sign** | "Undefined variable" | Always start with `$` |
| **Using spaces in names** | "Unexpected token" | Use underscores: `$user_name` |
| **Starting with number** | "Syntax error" | Start with letter: `$user1` |
| **Wrong case** | PHP is case-sensitive | Be consistent: `$name` vs `$Name` |
### Practice Exercises
**Try these to practice with variables:**
1. **Create Personal Info Variables:**
```php
<?php
$myName = "[YOUR_NAME]";
$myAge = [YOUR_AGE];
$myHeight = [YOUR_HEIGHT]; // In feet, like 5.8
$isStudent = true; // or false
$favoriteColor = "[YOUR_COLOR]";
echo "My name is $myName and I am $myAge years old.";
echo "I am $myHeight feet tall and my favorite color is $favoriteColor.";
?>
```
2. **Shopping Cart Variables:**
```php
<?php
$itemName = "Coffee Mug";
$price = 12.99;
$quantity = 3;
$total = $price * $quantity;
echo "You bought $quantity $itemName(s) for $$total";
?>
```
3. **Debug This Broken Code:**
```php
<?php
user-name = "John Doe";
age = 25;
price$ = 19.99;
echo "Hello " + user-name;
?>
```
### Real-World Examples
#### Example 1: Temperature Converter
```php
<?php
// Convert Celsius to Fahrenheit
$celsius = 25;
$fahrenheit = ($celsius * 9/5) + 32;
$isHot = $celsius > 30; // Boolean - is it hot?
$weatherReport = null; // No report yet
$weatherData = [
"temperature" => $celsius,
"condition" => "sunny",
"humidity" => 65
];
echo "$celsiusΒ°C equals $fahrenheitΒ°F";
echo "Is it hot? " . ($isHot ? "Yes!" : "No!");
?>
```
#### Example 2: Grade Calculator
```php
<?php
// Student grades
$mathScore = 85; // Integer
$scienceScore = 92.5; // Float
$englishScore = 78;
$average = ($mathScore + $scienceScore + $englishScore) / 3;
$isPassing = $average >= 70; // Boolean
$letterGrade = null; // Will be calculated later
$scores = [$mathScore, $scienceScore, $englishScore];
echo "Average score: " . round($average, 1);
echo "Passing? " . ($isPassing ? "Yes!" : "No!");
?>
```
#### Example 3: Social Media Post
```php
<?php
// Social media post data
$username = "tech_guru_2024";
$postContent = "Just learned PHP variables! π";
$likes = 42;
$shares = 7;
$isPublic = true;
$location = null; // No location tagged
$hashtags = ["#PHP", "#coding", "#webdev", "#learning"];
$postDate = date("Y-m-d H:i:s");
echo "$username posted: $postContent";
echo "Likes: $likes | Shares: $shares";
echo "Hashtags: " . implode(" ", $hashtags);
?>
```
### How to Write This in an Exam
**Clean, simple answer for semester exams:**
```
A PHP variable is a named container that stores data values.
Variables in PHP:
- Start with $ symbol (e.g., $name)
- Are dynamically typed (type determined by value)
- Follow naming rules: letters/underscores/numbers, no spaces
- Are case-sensitive ($name β $Name)
Main PHP data types:
1. String - text data ("Hello")
2. Integer - whole numbers (42)
3. Float - decimal numbers (3.14)
4. Boolean - true/false values
5. Array - multiple values ([1,2,3])
6. Null - no value (null)
```
### Key Takeaways
- **Variables are like labeled boxes** - name + value
- **Always start with `$`** - PHP's way of saying "this is a variable"
- **PHP figures out the type automatically** - smart and helpful!
- **Use meaningful names** - `$userAge` is better than `$x`
- **Check with `var_dump()`** - peek inside your boxes anytime
**Remember:** Good variable names make your code readable. Think "What would make sense to someone reading this tomorrow?"**
### How to write this in a semester exam
If you need a clean exam-style answer, you can write it like this (simple English, short, correct):
- A variable is a named memory location used to store data during program execution.
- In PHP, variables start with `$` and they do not need a type keyword.
- PHP is dynamically typed, so the type is decided by the value stored in the variable.
Common PHP data types you should mention:
- Integer (example: `20`)
- Float/Double (example: `99.50`)
- String (example: `"Aman"`)
- Boolean (example: `true`)
- Null (example: `null`)
- Array (example: `["red", "blue"]`)
Variable naming rules (easy marks):
- Must start with `$`
- After `$`, start with a letter or `_` (underscore)
- Can contain letters, numbers, `_`
- Case-sensitive: `$name` and `$Name` are different
### What to avoid (so your answers and code both stay correct)
- Donβt use a variable without setting it first. If you need to check, use `isset($x)` or `??` default.
- Donβt mix `==` and `===` randomly. For clean comparisons, prefer `===`.
- Donβt trust that input is a number. Form/URL input is usually a string, so cast it before math.
If you ever feel unsure about what a value is, print it:
```php
<?php
$value = "20";
var_dump($value);
echo gettype($value);
```
### The common confusion: "20" vs 20
These look similar, but they are not the same:
```php
<?php
$a = "20";
$b = 20;
var_dump($a === $b);
var_dump($a == $b);
```
- `===` means same value and same type
- `==` means PHP will try to compare after type conversion
For clean code, prefer `===` and keep types predictable.
### Type declarations (recommended)
PHP is dynamically typed, but modern PHP lets you declare parameter and return types. This catches mistakes early.
```php
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
echo add(2, 3);
```
With `strict_types=1`, PHP stops doing βhelpfulβ auto-conversions for typed parameters, so you notice bugs sooner.
### Useful casts (when input is string)
When values come from forms or URLs, they are usually strings. Convert them before using them:
```php
<?php
$qtyText = "3";
$priceText = "99.50";
$qty = (int) $qtyText;
$price = (float) $priceText;
echo $qty * $price;
```
### Constant vs variable (small but important)
A variable can change:
```php
<?php
$x = 10;
$x = 20;
echo $x;
```
A constant is a fixed value. In PHP you commonly write constants using `const`:
```php
<?php
const APP_NAME = "MyApp";
echo APP_NAME;
```
---
## Conclusion
In this article, we explored the core concepts of All about PHP - Variables and Types. Understanding these fundamentals is crucial for any developer looking to master this topic.
## Frequently Asked Questions (FAQs)
**Q: What is All about PHP - Variables and Types?**
A: All about PHP - Variables and Types is a fundamental concept in this programming language/topic that allows developers to perform specific tasks efficiently.
**Q: Why is All about PHP - Variables and Types important?**
A: It helps in organizing code, improving performance, and implementing complex logic in a structured way.
**Q: How to get started with All about PHP - Variables and Types?**
A: You can start by practicing the basic syntax and examples provided in this tutorial.
**Q: Are there any prerequisites for All about PHP - Variables and Types?**
A: Basic knowledge of programming logic and syntax is recommended.
**Q: Can All about PHP - Variables and Types be used in real-world projects?**
A: Yes, it is widely used in enterprise-level applications and software development.
**Q: Where can I find more examples of All about PHP - Variables and Types?**
A: You can check our blog section for more advanced tutorials and use cases.
**Q: Is All about PHP - Variables and Types suitable for beginners?**
A: Yes, our guide is designed to be beginner-friendly with clear explanations.
**Q: How does All about PHP - Variables and Types improve code quality?**
A: By providing a standardized way to handle logic, it makes code more readable and maintainable.
**Q: What are common mistakes when using All about PHP - Variables and Types?**
A: Common mistakes include incorrect syntax usage and not following best practices, which we've covered here.
**Q: Does this tutorial cover advanced All about PHP - Variables and Types?**
A: This article covers the essentials; stay tuned for our advanced series on this topic.