PHP variables are used to store data that can be used and manipulated throughout your script. Variables in PHP are identified by a $
sign, followed by the variable name.
To create a variable in PHP, simply write:
<?php
$name = "Alice"; // String variable
$age = 25; // Integer variable
$isStudent = true; // Boolean variable
?>
In the example above:
$name
stores a string value "Alice"
.$age
stores an integer value 25
.$isStudent
stores a boolean value true
.You can output the value of a variable using echo
or print
:
<?php
$name = "Alice";
echo "Hello, my name is $name.";
?>
Output:
Hello, my name is Alice.
Here are some rules for naming variables in PHP:
_
).$name
and $Name
are different).You can combine variables and strings using concatenation with a dot (.
):
<?php
$name = "Alice";
$greeting = "Hello, " . $name . "!";
echo $greeting;
?>
Output:
Hello, Alice!
Experiment with different types of variables and operations in PHP. Understanding how variables work is essential for mastering PHP and building dynamic web applications. Now you can learn about if else statements!