Day 3: Basics of PHP – Variables and Data Types
Variables in PHP
In PHP, variables are used to store data values. A variable name starts with the $
sign, followed by the name of the variable. PHP variables are case-sensitive.
Example:
<?php $name = "Amit"; $age = 25; $height = 5.9; $is_student = true; ?>
Data Types in PHP
PHP supports several data types for variables:
- String: A sequence of characters, enclosed within double quotes (
"
) or single quotes ('
).
$name = "Amit";
- Integer: A whole number without decimals.
$age = 25;
- Float (or Double): A number with a decimal point or an exponent notation (e.g.,
1.234
,2.0e3
).
$height = 5.9;
- Boolean: Represents
true
orfalse
.
$is_student = true;
- Array: A collection of key-value pairs or indexed elements.
$colors = array("Red", "Green", "Blue");
- Object: Instances of user-defined classes, which contain both data members (variables) and methods (functions).
[mycode]
class Person {
public $name;
public $age;
}
$person = new Person();
$person->name = “Amit”;
$person->age = 25;
[/mycode]
- NULL: Represents a variable with no value assigned.
$data = NULL;
Variable Naming Rules
- Variable names must start with a letter or underscore (
_
), followed by any number of letters, numbers, or underscores. - Variable names are case-sensitive (
$name
and$Name
are different variables).
Example: Using Variables and Data Types
[mycode]
<?php
$name = “Amit”;
$age = 25;
$height = 5.9;
$is_student = true;
echo “Name: ” . $name . “<br>”;
echo “Age: ” . $age . “<br>”;
echo “Height: ” . $height . “<br>”;
echo “Is student? ” . ($is_student ? “Yes” : “No”) . “<br>”;
// Arrays
$colors = array(“Red”, “Green”, “Blue”);
echo “Colors: ” . implode(“, “, $colors) . “<br>”;
// Object
class Person {
public $name;
public $age;
}
$person = new Person();
$person->name = “Amit”;
$person->age = 25;
echo “Person: ” . $person->name . “, Age: ” . $person->age . “<br>”;
// NULL
$data = NULL;
echo “Data: ” . var_export($data, true) . “<br>”;
?>
[/mycode]
Next Steps
Practice creating variables of different data types and printing their values. In Day 4, we will cover PHP operators, which allow you to perform operations on variables and values. Let me know if you have any questions or if you’re ready to move forward!