PHP Variables


Variables are "containers" for storing information.


Creating (Declaring) PHP Variables

In PHP, the variable starts with the $ sign, followed by the variable name:


Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>

After making the above statements, the $txt variable will hold Hello world!, the variable $x will hold the value of 5, and the variable $y will hold the value of 10.5.

Note: When assigning text values ​​to a variable, place quotes around the value.

Note: Unlike other programming languages, PHP does not have a dynamic declaration command. It is created when you start assigning value to it.


Think of flexible objects such as data storage containers.



PHP Variables

Variables can have a shorter word (such as x and y) or a more descriptive word (age, carname, total_ volume).

PHP flexibility rules:

  • The variable starts with the $ sign, followed by the name of the variable
  • The variable word should start with a letter or underscore character
  • A different name cannot start with a number
  • A different name may contain only alpha-numeric characters and underscore (A-z, 0-9, and _)
  • Very sensitive variables ($age and $AGE are two different variables)

Remember that PHP variables are sensitive!


Output Variables

PHP echo statement is often used to extract data from the screen.

The following example will show how to extract text and variables:


Example
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>

The following example will produce the same output as the example above:


Example
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>

The following example will yield a total of two variables:


Example
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>


PHP is a Loosely Typed Language

In the example above, note that we should not have told PHP what kind of data is variable.

PHP automatically associates data type to variable, depending on its value. Since data types are not set in a solid way, you can do things like add a character unit to the perfect number without causing an error.

In PHP 7, genre announcements have been added. This provides an option to specify the type of data that is expected when a job is announced, and by enabling a strict requirement, it will throw the "Critical Mistake" into a different format.