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
In this example, we created array using array() function.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];
Each value in an Array is called Array Element.Code:$fruits = array('grapes', 'apple', 'coconut', 'pineapple', 'mango', 'papaya', 'orange', 'lemon', 'strawberry', 'watermelon');
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
In the above example, line starting with // is commented. Try un comment the linePHP 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>';
to see how var_dump() prints the array.Code://var_dump($fruits);
Finding Number of Elements in an Array
array_count.php
count() function is used to count number of elements in an Array.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>';
Printing Array With foreach
For most real life programs, you need to use foreach() function to print value of an array.
array_foreach.php
Adding Elements to an ArrayPHP Code:<?php
$fruits = array('grapes', 'apple', 'coconut', 'pineapple', 'mango', 'papaya', 'orange', 'lemon', 'strawberry', 'watermelon');
foreach ($fruits as $fruit) {
echo $fruit;
echo '<br>';
}
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>';




Reply With Quote



Bookmarks