Array
Arrays is used to store multiple values in a variable.
Lets jump directly into some PHP code and learn how to use array.
Creating Array
fruits.php
PHP Code:
<?php
// create array
$fruits = array('grapes', 'apple', 'coconut', 'pineapple', 'mango', 'papaya', 'orange', 'lemon', 'strawberry', 'watermelon');
// lets print
echo $fruits[0];
echo '<br>';
echo $fruits[2];
echo '<br>';
echo $fruits[3];
echo '<br>';
echo $fruits[9];
In this example, we created array using array() function.
Code:
$fruits = array('grapes', 'apple', 'coconut', 'pineapple', 'mango', 'papaya', 'orange', 'lemon', 'strawberry', 'watermelon');
Each value in an Array is called Array Element.
Array Elements are separated by comma. This this array, we store string value (text), so they are enclosed inside single quote. Array can store numeric values too.
First element of the array, in our example grapes can be accessed using $fruits[0], here 0 is called Array Index. Array Index start from 0.
print_r() and var_dump()
print_r() and var_dump() functions can be used to print value of arrays. They are mostly used for debugging (to see raw value of an array/variable).
array_raw.php
PHP Code:
<?php
// create array
$fruits = array('grapes', 'apple', 'coconut', 'pineapple', 'mango', 'papaya', 'orange', 'lemon', 'strawberry', 'watermelon');
// lets print
echo '<pre>';
print_r($fruits);
//var_dump($fruits);
echo '</pre>';
In the above example, line starting with // is commented. Try un comment the line
Code:
//var_dump($fruits);
to see how var_dump() prints the array.
Finding Number of Elements in an Array
array_count.php
PHP Code:
<?php
// create array
$fruits = array('grapes', 'apple', 'coconut', 'pineapple', 'mango', 'papaya', 'orange', 'lemon', 'strawberry', 'watermelon');
$numberOfFruits = count($fruits);
echo '<p>We have ' . $numberOfFruits . ' fresh fruits in our store.</p>';
count() function is used to count number of elements in an Array.
Printing Array With foreach
For most real life programs, you need to use foreach() function to print value of an array.
array_foreach.php
PHP Code:
<?php
$fruits = array('grapes', 'apple', 'coconut', 'pineapple', 'mango', 'papaya', 'orange', 'lemon', 'strawberry', 'watermelon');
foreach ($fruits as $fruit) {
echo $fruit;
echo '<br>';
}
Adding Elements to an Array
array_add.php
PHP Code:
<?php
$fruits = array('grapes', 'apple', 'coconut', 'pineapple', 'mango', 'papaya', 'orange', 'lemon', 'strawberry', 'watermelon');
echo '<pre>';
print_r($fruits);
echo '</pre>';
echo '<p>I am going to add 2 more fruits to $fruits array.</p>';
$fruits[] = 'banana';
$fruits[] = 'cherry';
echo '<pre>';
print_r($fruits);
echo '</pre>';
Bookmarks