Tuesday, June 26, 2012

PHP Learning basics-PHP variables(1)

Basically, variables in php are containers that holds information. Variables starts with $, for example, you can name your variable $first_name, $last_name.... Be careful, variables can not start with a number, thus $4name would not be allowed in php as variable.
Some examples of variables:
$price=4;
$name="Jeff";
Something worth to notice here, when you assign a variable to a number, you don't need include "", however, when you assign variable to a string(I will explain later as we go through php in my blog), you either have to use "" or '', and a ; is always followed after you name the variable

To display a variable value, you can use "echo" or "print_r", for example:
$popsinger="Jeff Chang";
echo $popsinger ;(or print_r ($popsinger);)
For either of the command, you will get result "Jeff".
Of course, you can use "echo" command print more results once, looking at the example below:
$first_name="Jeff";
$last_name="Chang";
echo "Pop singer is", "$first_name," ", $last_name;
The result will be: Pop singer is Jeff Chang.

A little more complicated example:
$web="web";
echo "take a look at this $website";
What do we do now? we noticed that the variable "$website" does not even exist here, to tell php that we want to display website, we can use something like
echo "take a look at this {$web}site; Then you will get the desired result(It is just an example to show you something, of course i know i can just use $website="website", lol)

Look at this:
$name="NBA player";
$name="Yao Ming"
ok, why there is $ here?? if you look carefully, actually, we are creating a new variable here, which is $NBA player="Yao Ming"

To remove a variable, you can use: unset (variablename), such as unset($name), and you can unset more than one at a time, use "," to separate the variable name, such as unset($name, $NBAplayer)
Isn't that easy?? Emm... php language is not scary at all.... I think it is enough for today, we will have fun as we go through php.


View the original article here

No comments:

Post a Comment