In this tutorial we learn numeric array in detail.
Numeric array can stores numbers, strings etc.
Default array index will be represented by numbers.
By default array index starts from 0 and ends number of elements - 1.
In PHP array()
function is used to crate array. Inside this function we can pass multiple values separated by comma ,
array(Value1, Value2, ValueN);
<?php
$subject = array("C", "C++", "JAVA", "PHP");
echo $subject[3];
?>
array values accessed through its index.
<?php
$subject = array("C", "C++", "JAVA", "PHP");
//OR
$subject[ ]="C";
$subject[ ]="C++";
$subject[ ]="JAVA";
$subject[ ]="PHP";
//OR
$subject[0]="C";
$subject[1]="C++";
$subject[2]="JAVA";
$subject[3]="PHP";
?>
We can initialize array in all these ways but first is better than others because here we have created one $subject
and stores multiple subjects at different index.
This example prints all value in array.
<?php
$subject = array("C", "C++", "JAVA", "PHP");
for($i=0; $i < count($subject); $i++) {
echo $subject[$i].'<br />';
}
?>
Here we declare an array to store the subject in a variable $subject inside PHP script.
To fetch all the color value we use for loop.
Here we again use count($subject)
for count the element of an array. so it display all subject names.
count()
is a PHP library function that counts number of elements in array.
This example find sum of given array.
<?php
$sum = 0;
$arr = array(10, 20, 30, 40, 50);
for($i = 0; $i < count($arr); $i++) {
$sum = $sum + $arr[$i];
}
echo "Sum of given array = ".$sum;
?>
Ask Question