Arrays and PHP: A Primer - Single dimension arrays
(Page 4 of 6 )
As you should know by now, an array is simply a memory address, which is referenced by a variable name. Each indexes memory address is the same as its previous index, plus the size of the value stored in the current index. In PHP, you can declare an array using the array function, like in the following example:
<?
$Aarthur = array(
0 => 'Get Value 01',
1 => 'Get Value 02',
2 => 'Get Value 03',
3 => 'Get Value 04',
4 => 'Get Value 05'
);
?>This would create the variable $Arthur as an array containing five indexes from 0 to 4. The values of each index will also be filled in. The code below does exactly the same thing:
<?
$Arthur[0] = "Get Value 01";
$Arthur[1] = "Get Value 02";
$Arthur[2] = "Get Value 03";
$Arthur[3] = "Get Value 04";
$Arthur[4] = "Get Value 05";
?>The important thing to remember is that when we create our $Arthur variable using the array() function, we have to understand how they are accessed, and make sure we reference each index properly. For instance:
<?
$Arthur = array(
0 => 'Get Value 01'
);
?>This creates a new array variable named $Arthur. The value of 'Get Value 01' is pointed to by using the index of 0:
print $Arthur[0];However, if we have the following code:
<?
$Arthur = array(
'0' => 'Get Value 01'
);
?>This would create the $Arthur array in the same way, however instead of accessing the index numerically, we would now access it using the index '0', which is a string. We would change '0' to any other string we like:
<?
$Arthur = array(
'first_index' => 'Get Value 01'
);
?>There is one pitfall to avoid, however. When we're creating a new array variable, let's say that we used the following declaration:
<?
$Arthur = array(add => "Get Value Add");
?>Although there is nothing wrong with this declaration, it is not syntactically correct. We are trying to create a new array with one index named add. Because add is not defined anywhere, the PHP parsing engine may raise a warning error to alert you of this. The proper way to create an array like this would be:
<?
$Arthur = array("add" => "Get Value Add");
?>Notice now that we have a single-indexed array with one index named "add". We can now refer to our $Arthur array like this:
print $Arthur["add"]; // Would print "Get Value Add"This allows us to create arrays with indexes that can either be referenced numerically or by strings. We can go crazy and combine both numerical and string indexes, like this:
<?
$Arthur = array("first" => "Get Value Add", 1 => "Value One", "Two" => 2);
Print $Arthur["first"] . "<br>";
Print $Arthur[1] . "<br>";
Print $Arthur["Two"] . "<br>";
?>In the browser, our output would look like this:

Next: Multi-dimensional arrays >>
More PHP Articles
More By Tuna Celik