pTutorial

New way to learn PHP

PHP 5 Numeric Array

Numeric Array

Numeric array handled using an integer subscript to denote the position of the requested value.

You can easily create the array using array () function. Index of numeric array starts from zero and automatically incremented.

Syntax

array(element1,element2,element3..)

Example

<?php

$student = array("John","Smith","Brawn"); 

$numbers = array( 80, 50, 70, 120, 500);

echo $student[2]."
"; //third value echo $numbers[0];//first value ?>
Brawn
80

$student and $number both are the array variable and holding multiple value.

We can easily access the array value using index number that always start from zero.

In Line number 5 print third value of $student array variable and in line number 6 print first value of $number array variable.

Length of an array

Count () function is used to find the length of an ar0ray, its return number of element in an array.

Example of length of an array

<?php

$student = array("John","Smith","Brawn");
foreach( $student as $value )
{
echo "Name of student: $value 
"; } echo "number of element = ". count($student); ?>

Foreach loop is a special type loop that is used for access the array element as shown above.

Pass the array variable to the count() function to find the number of element of an array.

Access array using foreach loop and for

<?php

echo "First method
"; $numbers = array( 8, 5, 7, 12, 50); foreach( $numbers as $value ) /* First method to access array. */ { echo "Value is $value
"; } $len = count($numbers); echo "Second method
"; for( $i=0; $i< $len; $i++ ) /* Second method to create array. */ { echo "Value is $numbers[$i]"; echo"
"; } ?>

You can also use for loop for accessing the array with the help of count() function. Count function return the number of element in an array.

In above example $len is a variable that hold the number of element in an array so that for loop execute $len number of times.

Accessing particular element

<?php

$students = array
(
"john",
"brown",
"andrson"
,"xyv"
);
$a = $students[0];
echo $a."
"; $a1 = $students[3]; echo $a1."
"; echo $students[2]."
"; $num = array( 8, 5, 7, 12, 50); echo $num[2]."
"; echo $num[0]; ?>

You can also access a particular element of the array by using the index number as shown above.

Here student is an array type variable that hold the four element.

If you want to access the first element of the array use index number zero.

And if you want to access the fourth element of the student array use index number three.

Example

<?php

$student = array("John","Smith",120,"A",38);
foreach( $student as $value )
{
echo "Element: $value 
"; } ?>

You can keep string, number and character together in a single array variable and easily access the element of the array as shown above.

.

Index of numeric array is automatically incremented and start from zero.


QUOTES OF THE DAY

Saying is one thing, and doing is another.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER