PHP Datatypes

Posted: February 24, 2009

Programming languages all support different types of data, such as numbers or text.  But to the programming language, it gets even more specific.  There are many different kinds of numbers, for example, depending on whether it has a decimal or not.

Some common datatypes:
int  – an integer, or whole number without a decimal
float – floating point numbers, basically a number with a decimal
double – same as a float, but more specific.  It can hold longer values and more decimal places
bool – Boolean values.  Basically true or false
string – strings of text
array – a special type of variable which can hold a whole set of other variables inside it.

As we mentioned last lesson, some languages don’t let you change what type of data a variable holds.  So if you created a variable named foo that was an integer, you could not put a text string inside that variable later.  But you also could not put a floating point number inside that variable, even though they’re both numbers.

Also, unlike some languages, you do not have to ‘declare’ a variable.  Declaring a variable basically tells the programming language to set aside some memory for the variable for you to place values in.  In JavaScript, for example, you cannot be in the middle of a script and suddenly assign a value to variable foo.  You have to declare it before hand.

Example JavaScript:

first you have to declare it:

int foo;

then you could use it:

foo = 12;

With PHP, however, since you do not have to declare variables beforehand, you can create one whenever you need one.  For example, if you’re doing some things with numbers, and suddenly need to hold a value temporarily, you can do that with PHP by just assigning the value to the variable.

$foo = something

PHP implicitly declares $foo and sets the value into it whenever you first assign a value to it.

What this all means is that PHP gives you a lot of freedom with variables compared to other languages, but it also means you have to be careful.  Since you can place different kinds of values in a variable willy-nilly, you could call that variable later in a math operation, only to be foiled in your math plans because you forgot you put a string inside there earlier.

$foo = 1;<br />
Blah blah blah, more php code…<br />
$foo = ‘some string’;<br />
Blah blah blah, more php….<br />
$foo + 3

…  Uh, oh.  We forgot we made foo into a string.

Or, you might accidentally name a variable the same as a variable you used before, overwriting the values, not realizing why you’re getting wrong answers.

Or finally, if you misspell something when you’re assigning something to a variable, PHP will just create a new variable.  PHP won’t be able to tell you there’s an error.

$fooo = something;
echo $foo;

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Yahoo! Buzz
  • Propeller
  • Twitter

Leave a Reply