Mark’s Site

Pensieve for coding and golf :-)

All About Variables

By admin • Apr 16th, 2008 • Category: 1.2. Code Basics

Variables hold information. If you want to store a value of 1 or 100 (or more/less), we use an integer variable. If you want to store a string value of say, “this is my pet”, we use a string variable. Variables allow us to hold, in computer memory, information that we are passing around in our code. Some types of variables of PHP are below, under the Examples.

Rules

In PHP, variables cannot contain spaces, and cannot start with a number (or other special character as far as I’m aware). So some good rules to remember when you’re starting is, when you want to use a space in a variable name, use an underscore (_) character. Eg. If you wanted to call your variable “my integer”, you would name it as follows: $my_integer. And if you felt you need to include a number in your variable, just remember to never START your variable name with the number. So you could have $my_var1, but NOT $1_var. Get the picture?

Examples of Variables

<?php
//an integer
$some_variable = 5;

//a float
$some_variable = 5.65;

//a string
$some_variable = 'ten biscuits';

//an integer array
$some_variable = array(1,23,6,4);

//a string array
$some_variable = array("ten","mark", "bob", "jessica", "five");

//a multi-dimensional array (array within an array)
$some_variable = array(array(3,7,1), array(2,3,5));

//an object variable (advanced) - think of this as a collection of information, much like an array
$some_object->id = '5';
$some_object->name = 'Bob';
$some_object->phone = '12345678';
?>

As you can see, with PHP you don’t have to declare the variable as an integer, or string, PHP just figures that out. But if you are conducting calculations, it is always a good idea to cast your variable as the integer type, just in case PHP gets confused somehow. Casting is super easy. You just add ‘int’ to the start of your variable. As follows:

<?php
$some_var1 = 3;
$some_var5 = 66;
$total = (int)$some_var1 + (int)$some_var5;
?>

That will ensure that the calculation gets evaluated properly as two integer variables. You may not see a need at first, but if/when your code gets complicated and you are mixing strings and integers, the cast is a very useful tool.

admin is
Email this author | All posts by admin

Leave a Reply