HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP Variables

Creating (Declaring) PHP Variables

In PHP, creating (declaring) variables is straightforward and doesn't involve an explicit "declaration" statement like you might see in other programming languages. Instead, variables are implicitly declared when you assign a value to them for the first time.


• While it's true that PHP is a dynamically typed language, which means you don't explicitly declare types for variables like in some other languages, saying it doesn't analyze values or perform data type conversions isn't entirely accurate.

• After declaring a variable, it can be reused throughout the code.

• Assignment Operator (=) is used to assign the value to a variable.


Syntax of declaring a variable in PHP is given below:


$variablename=value;



Rules for declaring PHP variable:

1 • Start with a Dollar Sign ($): Every PHP variable name must begin with a dollar sign ($). This symbol differentiates variables from other elements in your code.
2 • Use Alphanumeric Characters and Underscores: The remaining characters in the variable name can be letters (a-z, A-Z), numbers (0-9), or underscores (_). Spaces are not allowed.
3 • Case-Sensitive: PHP variables are case-sensitive. This means that $age and $AGE are considered different variables.
4 • A PHP variable name cannot contain spaces.
5 • One thing to be kept in mind that the variable name cannot start with a number or special symbols.
6 • Begin with a Letter or Underscore: The first character of your variable name cannot be a number. It must be a letter (a-z, A-Z) or an underscore (_).


PHP Variable: Declaring string, integer, and float


<?php $str="hello string";
$x=200;
$y=44.6;
echo "string is: $str ";
echo "integer is: $x ";
echo "float is: $y ";
?>

Output:

string is: hello string
integer is: 200
float is: 44.6