This tutorial will hopefully explain to you what arrays are, and how they are used.
An array is useful for when you want to store multiple values without having to define multiple variables.
Defining the Array
Defining the Array is simple enough:
The first two values in our array have no key associated with. This means that we can't access these values unless we know there position within the array. An array with at least one value that doesn't have a key linked to it has a starting index of 0. Accessing values is very easy:PHP Code:$array = array("1", "2", "My_Key" => "My Value"); //Defining our array.
The above will output '1'. To the page.PHP Code:Echo $array[0];
As expected, to get the value '2', the following code can be applied:
However, accessing a value in an array with a linked key is slightly different. We use the key's name:PHP Code:Echo $array[1];
Just as you might imagine, this will output "My Value".PHP Code:Echo $array['My_Key'];
The last way I'm going to cover for getting the values for an array is to loop through it.
This will EchoPHP Code:foreach ($array as $part){
Echo $part . "<br>";
}
"1
2
My Value".
Adding Values to Arrays
To add a value to an already existing array is also pretty simple.
If you don't want to link a key to it, empty square braces are required.
If you do want to link a key, these braces will need to be filled.PHP Code:$array[] = "New Value";
Removing ArraysPHP Code:$array['Key_Name'] = 'My New Value';
Now that we've covered adding values to an array, lets go through how to remove an array.
To remove the array completely, simply call the 'unset()' function on the array:
If, however, you only want to remove one element in the array, you will need to know it's index location or it's key name.PHP Code:unset($array);
After unsetting an element from the array, always call the array_values() function.PHP Code:unset($array['My_Key']);
This will reset the index of the array.PHP Code:$array = array_values($array);
I hope this tutorial is useful.
Thread moved by Jordan (Forum Super Moderator): From 'Designing & Development' to here as more suited







Reply With Quote




