PHP Indexed Array - php scripts -

PHP Indexed Array

PHP Summer Training/Internship with 2 Live Projects in Noida Fee is only 5500/-Click here to Book Your Seat


PHP numeric array

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( ) is used to create array. Inside this can pass multiple values separated by comma( , )


10 red

Note: array values accessed through its index.

In the above example
An array of multiple values is assign to a variable ($arr) on corresponding index starts from 0.
Another array of variable name($col) is declare in which some color’s name is stored.
we can easily access the value of an array referring its index no.
Next step we have print the array with their index $arr[0] and $col[0] so
The output display the first value of both array : 10 red

We can define array in three ways.

We can initialize array in all these ways but first is better than others because here we have created one $col and stores multiple colors at diff index.

Loop Through an Numeric(Indexed) Array

Find the sum of given array

Sum of given array = 150

In the above example
$sum variable hold value = 0, An array is declare with five element(10 to 50).
we can do it by the use of for loop because we know in advance how many times a loop run,here we start counting form($i= 0 to count($arr) : is used to count the no of element embedded in an array.
Here count( ) returns 5 elements . so it will display the sum using($sum=$sum+$arr[$i];).
$arr[$i] is used to fetch the value According index value(0,1,2,3,4)

Display all the colors name i.e stored in array

blue red green white pink

Note: Here count() is a function that counts number of elements.

In the above example
we declare an array to store the color in a variable $col inside PHP script.
To fetch all the color value we use for loop.
here we again use count($arr) for count the element of an array. so it display all color names.

Find Sum of even and odd numbers stored in array

Sum of even = 36
Sum of odd = 39

In the above example
An array is declare with name($arr) it store Six values. To find out the sum of even and odd numbers.

we use if else condition inside the for loop. count the array element corresponding to their index number.

statement is execute if ($arr[$i]%2==0) is true. otherwise else statement is execute.

Print the sum of even and Odd numbers.

Latest Trending Technologies