Getting Started with PHP Variables


Using Variables in PHP

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.

Declaring Variables

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";
?>

Output:

Name: Zaid

Age: 19

Height: 5.9 feet

Variable Reassignment

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;
?>

Output:

Initial Value: 10

Reassigned Value: Hello, AIT!

Variable Types in PHP

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
?>

Output:

Integer: 42

String: PHP Variables

Float: 3.14

Array Element: Apple

Using variables efficiently helps in managing and processing data within a PHP script.