Variables in PHP are used to store data, like strings, integers, or arrays. A variable in PHP starts with a $
sign, followed by the name of the variable.
Variables are declared by using the $
symbol, followed by the variable name and the assignment operator (=
).
<?php
$name = "Zaid";
$age = 19;
$height = 5.9;
echo "Name: " . $name . "<br>";
echo "Age: " . $age . "<br>";
echo "Height: " . $height . " feet";
?>
Name: Zaid
Age: 19
Height: 5.9 feet
Variables can be reassigned to different values, even different data types.
<?php
$value = 10; // Initially an integer
echo "Initial Value: " . $value . "<br>";
$value = "Hello, AIT!"; // Now a string
echo "Reassigned Value: " . $value;
?>
Initial Value: 10
Reassigned Value: Hello, AIT!
PHP variables can store different types of data, such as integers, floats, strings, and arrays.
<?php
$integerVar = 42; // Integer
$stringVar = "PHP Variables"; // String
$floatVar = 3.14; // Float
$arrayVar = array("Apple", "Banana", "Cherry"); // Array
echo "Integer: " . $integerVar . "<br>";
echo "String: " . $stringVar . "<br>";
echo "Float: " . $floatVar . "<br>";
echo "Array Element: " . $arrayVar[0]; // Accessing array element
?>
Integer: 42
String: PHP Variables
Float: 3.14
Array Element: Apple
Using variables efficiently helps in managing and processing data within a PHP script.