What are Variables ?

A variable in PHP is a name of memory location that holds data. A variable is a temporary storage that is used to store data temporarily.
In PHP, a variable is declared using $ sign followed by variable name.

Loosely typed language : PHP is a loosely typed language, it means PHP automatically converts the variable to its correct data type.

Syntax :  $variablename=value;

How to Declaring string, integer and float etc.

Example of store string, integer and float values in PHP variables.

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

Output:
String is: hello string
Integer is: 200
Float is: 44.6

Rules of making Variable in PHP.

  • PHP variables must start with letter or underscore only.
  • PHP variable can’t be start with numbers and special symbols.
  • PHP variable starts with the $ sign, followed by the name of the variable.
  • PHP variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • You cannot use a PHP keywords (reserved word) as a variable name.
  • Uppercase characters are distinct from lowercase characters.
  • After declaring a variable it can be reused throughout the code.
  • A variable does not need to be declared before adding a value to it.
  • PHP automatically converts the variable to the correct data type, depending on its value.
  • The assignment operator (=) used to assign value to a variable.

Example

<?php 
// Valid 
$a="hello";  //letter (valid) 
$_b="hello"; //underscore (valid) 

echo "$a <br/> $_b"; 
/*
Output 
hello
hello
*/
// Invalid
$4c="hello"; //number (invalid) 
$*d="hello"; //special symbol (invalid) 

echo "$4c <br/> $*d"; 
/*
Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE) 
Parse error: syntax error, unexpected '*' (T_LNUMBER), expecting variable (T_VARIABLE) 
*/
?>

Case sensitive in Php

Yes PHP is Case Sensitive If you defined variable in lowercase, then you need to use it in lowercase everywhere in program.

Example : if i define variable $name="Arvind Ahir"; then we must need to use $name. $NAME will not work because of variable names and function name are case sensitive. So variable name “name” is different from Name, NAME, NaMe , NAme .

<?php 
$color="red"; 
echo "My car is " . $color . "<br>"; 
echo "My house is " . $COLOR . "<br>"; // Error Undefined variable: COLOR 
echo "My boat is " . $coLOR . "<br>";  //Error Undefined variable: coLOR 
?>
(Visited 82 times, 1 visits today)
Share with Friends :
Written by:

Leave a Reply

Your email address will not be published. Required fields are marked *