start learning
Image 1
501010112

Variables PHP

In PHP, variables are used to store and manipulate data. Here, I'll provide you with definitions, examples, and clarifications for PHP variables.


Variable Declaration


$name = "John";
$age = 25;

In this example, $name and $age are two variables. $name stores a string, and $age stores an integer.


Variable Assignment

You can assign values to variables using the assignment operator =


$fruit = "apple";
$quantity = 10;
 

In this example, we assigned the string "apple" to the $fruit variable and the integer 10 to the $quantity variable.


Variable Data Types


$name = "John";     // $name is a string
$age = 25;          // $age is an integer
$price = 3.99;      // $price is a float
$isStudent = true;  // $isStudent is a boolean
 

Variable Scope


$globalVar = 42; // This is a global variable
function myFunction() {
    $localVar = 10; // This is a local variable
    echo $globalVar; // Accessing a global variable within a function
}
myFunction();
echo $localVar; // This will result in an error; $localVar is not accessible here
 

Variable Interpolation


$name = "Alice";
echo "Hello, $name!";
// Output: Hello, Alice!
 

Concatenation

You can concatenate (join) variables and strings using the . operator.


$first_name = "John";
$last_name = "Doe";
$full_name = $first_name . " " . $last_name;
echo $full_name;
// Output: John Doe
 

Variables are essential in PHP for storing and manipulating data. Understanding how to declare, assign, and use variables is fundamental to writing PHP scripts and building dynamic web applications.