Introducing PHP Variables

In PHP, you can use something called a ‘variable‘ to store values or reference to things. It’s like a container which you can put some thing or things inside which can be easily passed around.

This variable is denoted by a dollar sign ‘$’, and must be followed by either a alphabet letter or an underscore ‘_’; the rest of the name can be any alphabets, numbers or underscore character.

Variable names are also case sensitive, so you need to be careful about using cap.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
 
/* these are valid variables */
$n; 
$_n; 
$my_name5;
 
/* these are NOT valid variables */
$5
$*un
 
/* these are NOT the same variables, they will be treated as 2 different ones */
$myName;
$MYNAME;
 
?>

To assign a value to a variable, you use the assignment operator ‘=’ (which is the equals sign) .

1
2
3
4
5
6
7
8
<?php
/* assigning the value of 10 to variable number */
$number = 10;
 
/* print out the value stored in the variable number */
print ($number);
 
?>

When you have a values stored inside variables, you can perform operations on them, for example, you can perform mathematical functions if the variables are numbers.

1
2
3
4
5
6
7
8
9
10
11
<?php
/* assigning the value of 10 to variable number */
$number = 10;
 
/* let's add 5 to number using the * operator */
$number = 10 * 5;
 
/* print out the value stored in the variable number */
print ($number);
 
?>

Now, the $number variable contains 50, and not 10.

PHP have different types of variables, these are the most common types you’ll likely to use often:

  • Booleans
  • Integers
  • Floats
  • Strings
  • Arrays
  • Objects

You can find out more about the different types from the PHP main site.

Luckily, PHP is smart enough to detect which variable type from the value being assigned to it. So, as a programmer, you don’t need to explicitly say what the variable type should be. But if you want to, PHP provides functions like settype() or cast the variable.

Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
<?php
/* assigning the value of 10 to variable number */
$number = 10;
 
/* assigning a string to variable label */
$label = "My number is ";
 
/* print out the 2 variables as a string */
print ("$label $number");
 
?>

If you have noticed, $number is an Interger type because you’ve assigned a numeric number to it, and $label is a String type because you’ve assigned a string to it. But when you call the print() function, PHP automatically knows that it needs to treat $number as a String type, and outputs everything as a String.

To find out more I suggest you visit these pages on the PHP site:

http://www.php.net/manual/en/language.types.php
http://www.php.net/manual/en/language.variables.php

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
Other similar posts:


Leave a Reply

Google