When writing your code you might need to store a large variable set outside of your database. It will surely be bad practice to save each of the variables separately. Keeping these variables in an array is the best way to go about it, especially if the data items are of the same data type (though arrays can hold varying data types together).
An array is a special variable that stores multiple values at once. If there is a list of items to be stored, it is best to store it in an array. Arrays can be very helpful in writing PHP codes.
For example:
$myBestFruits = array('mango','orange','apple');
$counter = 0;
while($counter <= count($myBestFruits)-1)
{
echo $myBestFruits[$counter];
$counter++;
}
The while loop will end if the counter has the value 2
, which equals the highest array index 2
.
In PHP, arrays are declared as shown below:
$myArrayName = array(/*array values separated by commas*/)
Use the array()
with the arguments as the items to be stored. In PHP, arrays are of a different type.
PHP has three basic types of arrays.
$myBestFruits = array('apple','orange','mango','pineapple');
echo $myBestFruits[0];
The output of this will be apple
.
The indexes can also be assigned manually to suit your need.
$myBestFruits[0]="mango";
$myBestFruits[1]="apple";
$myBestFruits[2]="pineapple";
$myBestFruits[3]="orange";
With this, the output of the echo
in the code above will now be mango
instead of apple
.
$myBestFruits = array("firstbest"=>"mango","secondbest"=>"orange");
echo $myBestFruits['firstbest'];
The output will be mango
.
An array can be looped using the foreach
loop, and also the length can also be determined using the count()
parsing the name of the array as an argument. We can perform other operations on an array, like append()
, sort()
, etc. Now to the third type.
$myBestFruits = array(
array("mango","green","single-seed"),
array("orange","yellow","multi-seed"),
array("apple","green","less-seed"));
echo $myBestFruits[0][2];
The output of the above code would look like this: single-seed
.
Working with arrays can be very tricky, but getting a hold of the concept will ease your coding tasks.