Php Variables

There are variables in programming, just like x and y in mathematical formulas. Whatever value we give, it represents that value wherever it is used. There are several types of variables depending on the data they represent. Since PHP automatically detects the data type, we do not need to specify these types when defining variables. In some cases, we can specify the variable type instead of leaving it to php to determine.  

Integer        Represents integers such as 3, 5, 4566. . ;

String           text containing numbers and symbols. “Today is the 28th day of the month.” like… 

Double        Decimal numbers like 3,444 

Float            Dotted numbers like 34,678 

Boolean      It takes two values. true (1) or false (0). Logical   It is used in comparisons

We need to follow certain rules when defining variables.

All variables in PHP start with $. A variable cannot start with a number. It cannot contain spaces. The variable name cannot contain any characters or symbols other than letters of the English alphabet, numbers and _.

Assigning values ​​to variables

After determining the variable name, we write = and then write the value of the variable. If the value of the variable is a string, we write it between " " or ' '. We do not use any quotation marks in numbers. If we use it, the data type will be string, not integer. This prevents us from performing mathematical operations with this variable.   


$text = "Echo function prints to the screen";
echo $text;


Learning the data type

We use the gettype() function to find out the data type of a variable.   


$text = "Echo function prints to the screen";
echo gettype($text);


Changing the data type

We can change the data type with the settype() function. String data type cannot be converted. For example, we can convert decimal numbers to integers.   


$number = 2.5;
settype($number, integer);
echo $number;

When you run the code, 2 is printed on the screen. There is also a shorter way to change the data type. When assigning to a variable, we can add the data type (type) in front of the value.   


$trials = "123,456,789 attempts";
$a = (int)$try; // When we print, the output is: 123
$two = (float)$try; // Output: 123.456
$uc= (string)$test; // Output: 123,456,789 attempts