So, you’re ready to handle data in PHP? Awesome! But wait—how do you store data, and what kinds of data can PHP handle? No worries, my friend! In this guide, we’ll break down variables and data types in PHP so you can write code that actually does something useful.
What is a Variable?
A variable is like a storage box where you can put your data. In PHP, all variables start with a $ sign, followed by the variable name.
$name = "Alice"; // A string
$age = 25; // An integer
$price = 19.99; // A float
$isPHPFun = true; // A boolean
Rules for Naming Variables
- Must start with a $ (e.g.,
$myVar
) - Can contain letters, numbers, and underscores (
_
). - Cannot start with a number (e.g.,
$1variable
) - Cannot contain spaces (e.g.,
$my variable
).
Data Types in PHP
PHP is loosely typed, meaning you don’t have to specify the data type—it figures it out for you. Here are the main ones:
String (Text)
Used for storing words, sentences, or even paragraphs.
$text = "Hello, PHP!";
echo $text; // Output: Hello, PHP!
Integer (Whole Numbers)
Used for counting, IDs, ages, etc.
$age = 30;
echo $age; // Output: 30
Float (Decimal Numbers)
For prices, percentages, and other real numbers.
$price = 9.99;
echo $price; // Output: 9.99
Boolean (True or False)
Perfect for making decisions in your code.
$isCodingFun = true;
if ($isCodingFun) {
echo "Yes, PHP is fun!";
}
Array (Multiple Values)
Think of it as a list of items.
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[1]; // Output: Banana
NULL (Empty Variable)
Used when a variable has no value.
$nothing = NULL;
Type Checking & Conversion
Sometimes, you need to check or change a variable’s type.
Checking Type
var_dump($age); // Shows data type and value
Type Conversion
$number = "10"; // String
$convertedNumber = (int) $number; // Now it's an integer
Understanding variables and data types is crucial for PHP development. Now that you know how to store and manage data, you’re ready for the next big thing: Operators and Expressions in PHP!
0 Comments