PHP

PHP Numeric Array

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 ,

Syntax:

array(Value1, Value2, ValueN);

Example:

<?php
    $subject = array("C", "C++", "JAVA", "PHP");        
    echo $subject[3];
?>
Note:

array values accessed through its index.

Output:

Tutorialik.com
PHP

Creating Array

We can create array in following three ways.

Example:

<?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.


Loop Through an Numeric(Indexed) Array

if we want to perform any operation on array, we must use any loop.

Example:

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.

Note:

count() is a PHP library function that counts number of elements in array.

Output:

Tutorialik.com
C
C++
JAVA
PHP

Example:

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;
?>

Output:

Tutorialik.com
Sum of given array = 150



Subscribe us on Youtube

Share This Page on


Ask Question