In PHP, a variable is a container that stores a value or a reference to a value. A variable is represented by a dollar sign ($) followed by the variable name. Variable names are case-sensitive.
Here are some examples of declaring variables in PHP:
<?php
$name = "John";
$age = 30;
$salary = 45000.50;
$is_employed = true;
$colors = array("red", "green", "blue");
$person = new stdClass();
?>
In the above example, $name
is a string variable that stores the value “John”, $age
is an integer variable that stores the value 30, $salary
is a floating-point variable that stores the value 45000.50, $is_employed
is a Boolean variable that stores the value true, $colors
is an array variable that stores the values “red”, “green”, and “blue”, and $person
is an object variable that stores a new instance of the stdClass
object.
You can use variables in PHP just like you would in any other programming language. For example, you can perform arithmetic operations on numeric variables, concatenate strings, and access array elements using their keys.
<?php
$x = 10;
$y = 5;
$sum = $x + $y;
$difference = $x - $y;
$product = $x * $y;
$quotient = $x / $y;
$remainder = $x % $y;
$greeting = "Hello, ";
$name = "John";
$message = $greeting . $name;
$colors = array("red", "green", "blue");
echo $colors[0]; // "red"
?>