PHP Variables
In PHP, variables are used to store and manipulate data. They are containers that hold values of various types, such as numbers, strings, arrays, or objects. Here’s some information about PHP variables:
- Variable Naming:
- Variable names in PHP start with a dollar sign ($) followed by a letter or underscore.
- They can contain alphanumeric characters and underscores.
- Variable names are case-sensitive, so “$name” and “$Name” are considered different variables.
- Variable Assignment:
- Variables are assigned values using the assignment operator (=).
- The value can be of any data type, and PHP automatically determines the type based on the assigned value.
$name = "John"; // Assigning a string value
$age = 25; // Assigning an integer value
$prices = [10, 20]; // Assigning an array
3. Variable Types:
- PHP is a loosely typed language, meaning you don’t need to declare variable types explicitly.
- Variables can change their types during execution.
php
$name = "John"; // string
$age = 25; // integer
$isStudent = true; // boolean
$price = 10.99; // float
$data = null; // null
4. Variable Scope:
- Variables have different scopes, which determine their visibility and accessibility in different parts of the code.
- The most common scopes are global and local.
- Global variables can be accessed from anywhere in the code, while local variables are limited to a specific block or function.
php
$globalVar = 10; // Global variable
function myFunction() {
$localVar = 20; // Local variable
echo $globalVar; // Accessing the global variable from inside a function
}
echo $localVar; // Error: Trying to access a local variable from outside its scope
5. Variable Interpolation:
- In double-quoted strings, variables can be directly interpolated by enclosing them in curly braces ({}).
- This allows you to include variables within strings without concatenation.
php
$name = "John"; echo "Hello, {$name}!"; // Output: Hello, John!
These are the basics of working with variables in PHP. They provide flexibility in storing and manipulating data within your PHP scripts.