PHP Variables: PHP Variable: Declaring String, Integer, and Float
PHP Variables: PHP Variable: Declaring String, Integer, and Float
<="" p="">
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some imp
variables:
o As PHP is a loosely typed language, so we do not need to declare the data types of t
analyzes the values and makes conversions to its correct datatype.
o After declaring a variable, it can be reused throughout the code.
o Assignment Operator (=) is used to assign the value to a variable.
1. $variablename=value;
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a number or special
o PHP variables are case-sensitive, so $name and $NAME both are treated as different variab
File: variable1.php
1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>
Output:
1. <?php
2. $x=5;
3. $y=6;
4. $z=$x+$y;
5. echo $z;
6. ?>
Output:
11
File: variable3.php
1. <?php
2. $color="red";
3. echo "My car is " . $color . "<br>";
4. echo "My house is " . $COLOR . "<br>";
5. echo "My boat is " . $coLOR . "<br>";
6. ?>
Output:
My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is
PHP Variable: Rules
PHP variables must start with letter or underscore only.
File: variablevalid.php
1. <?php
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4.
5. echo "$a <br/> $_b";
6. ?>
Output:
hello
hello
File: variableinvalid.php
1. <?php
2. $4c="hello";//number (invalid)
3. $*d="hello";//special symbol (invalid)
4.
5. echo "$4c <br/> $*d";
6. ?>
Output:
Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE
or '$' in C:\wamp\www\variableinvalid.php on line 2
← PrevNext →
ADVERTISEMENT
ADVERTISEMENT
Feedback
Splunk
SPSS
Swagger
Transact-SQL
Tumblr
ReactJS
Regex
Reinforcement Learning
R Programming
RxJS
React Native
Python Pillow
Python Turtle
Keras
Preparation
Aptitude
Reasoning
Verbal Ability
Interview Questions
Company Questions
Trending Technologies
Artificial Intelligence
AWS
Selenium
Cloud Computing
Hadoop
ReactJS
Data Science
Angular 7
Blockchain
Git
Machine Learning
DevOps
ADVERTISEMENT
B.Tech / MCA
DBMS
Data Structures
DAA
Operating System
Computer Network
Compiler Design
Computer Organization
Discrete Mathematics
Ethical Hacking
Computer Graphics
Software Engineering
Web Technology
Cyber Security
Automata
C Programming
C++
Java
.Net
Python
Programs
Control System
Data Mining
Data Warehouse
ADVERTISEMENT