Friday 2 September 2011

PHP Tutorial Ch-02 Variables in PHP

CHAPTER-2 Variables in PHP

Consider the following script (Just look at it. Don’t copy it, from here on I advice that you read the programs, understand them and then try it on your own):-

<html>
<head>
<title>Variables Trial</title>
</head>
<body>
<?php
$var=10;
echo "Value of variable var is = ".$var;
?>
</body>
</html>

The above PHP code has 2 lines. In the first line we define a new variable var with the value 10.

In PHP, variables are declared by prefixing the variable name with a $ sign. You do not need to specify the type of variable. It is automatically set according to the type of value that is stored in it. In the above code variable $var stores a value 10 which is of integer type. So, variable $var is an integer variable. We may even assign $var a value other than integer type. Consider this code-


<html>
<head>
<title>Variables Trial</title>
</head>
<body>
<?php
$var=10;
echo "Value of variable var is = ".$var;
$var="Your Name";
echo "Value of variable var is = ".$var;
?>
</body>
</html>

In the above code $var is first assigned an integer type value of 10 (as in the previous code). After displaying its value onto screen $var is assigned with a string type value. On echoing $var now that string is displayed. So, you can see that in PHP, variables can be of any datatype depending on the value stored in it.

Note: In the echo statements of the above two programs the ‘.’(dot) operator is used. The dot operator is used to concatenate two or more strings or strings with variables. The value returned by the dot operator is a string.

Note: Since PHP is a case sensitive language, so variables in PHP are also case sensitive. This means that a variable $var is different from $Var.

Note: Variables names in PHP must satisfy the following rules:-
  • A variable name must start with a letter or an underscore "_"
  • A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
  • A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString)

Note: For a list of all the supported datatypes in PHP follow this link http://php.net/manual/en/language.types.php

2 comments:

  1. Please post more chapters in PHP.

    ReplyDelete
  2. I have posted chapters 3 and 4. Here's the link to chapter 3 http://andcbuddies.blogspot.com/2011/09/php-tutorial-ch-03-arrays-in-php.html

    ReplyDelete