Creating (Declaring) PHP Variables
PHP variables are easy to spot because each name begins with a $ sign. There is no separate declaration step: the variable comes into existence when you first give it a value.
Create variables
$txt receives a string and $x an integer, and echo prints each of them:
Output: PHP script
<?php
$txt = "Hello World!";
$x = 5;
echo $txt;
echo "\n";
echo $x;
?>
PHP Variables
Names can be as short as $x and $y, or they can describe the contents, as in $age, $carname and $total_volume.
When choosing a name, follow these rules:
- Write a
$sign first, with the name right after it. - Begin the name with a letter or an underscore.
- Never begin the name with a number.
- Use only letters, digits and underscores (
A-z,0-9, and_). - Watch the case, because
$ageand$AGEare separate variables.
Output Variables
To show something on the screen, PHP code often uses the echo statement. It can print plain text, the contents of a variable, or both.
Output a string and a variable
The text and the variable are joined with a dot, and echo prints the whole sentence:
Output: PHP script
<?php
$txt = "PromptCookbook";
echo "I love " . $txt;
?>
Sum of two variables
echo can print the result of a calculation too, such as adding two variables:
Output: PHP script
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
PHP is a Loosely Typed Language
You may have noticed that none of these examples states a data type. PHP works it out from the value and attaches it to the variable for you. Because the rules are this relaxed, you can even add a numeric string to an integer and get no error.
PHP 7 brought in type declarations as an option. They let you say which data type a function expects when you declare it, and if you turn on the strict requirement, a type mismatch causes a Fatal Error.