Variables in PHP
Variables are the fundamental building blocks of any programming language, and PHP is no exception. A variable in PHP is a named container that holds a value, which can be a string, integer, float, boolean, array, object, or NULL.
Syntax:
$variable_name = value;
Examples:
$name = 'saifosys'; // string variable
$age = 30; // integer variable
$height = 5.9; // float variable
$is_admin = true; // boolean variable
$colors = array('red', 'green', 'blue'); // array variable
$user = new stdClass(); // object variable
$null_value = NULL; // NULL variable
Types of Variables:
1. String: A sequence of characters, enclosed in single quotes or double quotes.
$string = 'Hello, saifosys!';
2. Integer: A whole number, without any decimal points.
$integer = 123;
3. Float: A decimal number, with a fractional part.
$float = 3.14;
4. Boolean: A true or false value, often used for conditional statements.
$boolean = true;
5. Array: A collection of values, indexed by keys or numbers.
$array = array('saifosys', 'php', 'website');
6. Object: An instance of a class, with properties and methods.
$object = new stdClass();
7. NULL: A variable with no value, often used to indicate absence or default values.
$null = NULL;
Variable Naming Rules:
1. Start with a dollar sign ($).
2. Followed by a letter or underscore (_).
3. Can contain letters, numbers, and underscores.
4. Case-sensitive.
Variable Scope:
1. Local: Accessible only within the current function or scope.
2. Global: Accessible from anywhere in the script.
3. Static: Retains its value between function calls.
Passing Variables:
1. By Value: A copy of the variable is passed.
function foo($x) {
$x = 10;
}
$y = 5;
foo($y);
echo $y; // outputs 5
2. By Reference: The original variable is passed.
function foo(&$x) {
$x = 10;
}
$y = 5;
foo($y);
echo $y; // outputs 10
Variable Operators:
1. Assignment: =
$x = 5;
2. Addition: +
$x = 5;
$y = 3;
$sum = $x + $y;
3. Subtraction: -
$x = 5;
$y = 3;
$diff = $x - $y;
4. Multiplication: *
$x = 5;
$y = 3;
$product = $x * $y;
5. Division: /
$x = 5;
$y = 3;
$quotient = $x / $y;
6. Modulus: %
$x = 5;
$y = 3;
$remainder = $x % $y;
Best Practices:
1. Use meaningful variable names.
2. Use the correct data type.
3. Avoid using global variables.
4. Pass variables by reference when necessary.
5. Use variable operators to perform operations.
By mastering variables in PHP, you can write efficient and effective code to manipulate and store data.