Variables in PHP: Declaration and Printing

The variables in PHP are simply declared as

$varname = value;

Take for example

$days = 7;

Now you notice that we did not explicitly specify the type of the variable like many programming languages (C, C++, Java). In PHP, you don’t have to declare types. Let’s see a floating point number.

$pi = 3.14159265;

Now let’s see how we can print the variables

echo $days;

The output is

7

Now if you want to print the various variables. You can use the newline character represented by n to separate the variables

echo $days, "n";
echo $pi, "n";

Note how we used the comma as a separator between the variable and the newline character.
The output is

7
3.14159265

Next we describe the variables with strings.

echo $days, " ", $pi, "n"; 
echo "The number of days in a week is ", $days, "n";
echo "The value of PI is ",$pi, "n"; 

The output is

7 3.14159265
The number of days in a week is 7
The value of PI is 3.14159265

Now it is possible to put the variable within the double quotes, which will help us to avoid the multiple use of commas and the double quotes

echo "The number of days in a week is $daysn";
echo "The value of PI is $pin"; 

The output is

The number of days in a week is 7
The value of PI is 3.14159265

Now let’s see what happens when we use single quotes instead of double quotes

echo 'The number of days in a week is $daysn';
echo 'The value of PI is $pin'; 

The output is

The number of days in a week is $daysnThe value of PI is $pinJoys of Programming

As you can see, whatever is put in a single quotes is printed as it is. So variable names, newline characters will have no significance if put in single quotes

The complete example

$days = 7; /*The number of days in a week*/
$pi = 3.14159265; /*The value of PI*/

echo $days, "n";
echo $pi, "n";

echo $days, " ", $pi, "n"; 
echo "The number of days in a week is ", $days, "n";
echo "The value of PI is ",$pi, "n"; 

echo "The number of days in a week is $daysn";
echo "The value of PI is $pin"; 

echo 'The number of days in a week is $daysn';
echo 'The value of PI is $pin'; 

The output

The complete example


3.14159265
7 3.14159265
The number of days in a week is 7
The value of PI is 3.14159265
The number of days in a week is 7
The value of PI is 3.14159265
The number of days in a week is $daysnThe value of PI is $pin

Similarly we can use variables to declare strings

$name = "Joys of Programming";
echo $name, "n";

The output

Joys of Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s