Join Class

How to create Array in php application

Php Array is a collection type variable, we can store multiple values in array, like other programming language we also can define array in php with following syntax.

Array is immutable and index starts from zero, to define an array in php, we can use array key word like $colors=array("Green","Yellow","Blue","Red");.

echo "I like " . $colors[0] . ", " . $colors[2] . " and " . $colors[3] . ".";

In above example we see the result as “I like Green, Blue and Red ”, Yellow will not be there, because the array element $colors[1] has not been mentioned in our above statement.

So now you know we can create array using array();

To find how many elements are there in array, we can use count() method to get Array length.

Type of Array in Php

There are three types of array in php programming. Indexed array, Associative array and Multidimensional array.

Indexed arrays, Array that use numeric index number to retrieve the value.

$fruits = array("Banana", "Apple", "Papaya", "Grape");

// We could have also written like below 


// To retrieve value from array we can use index number
echo $fruits[3];


Associative arrays in php, Array that use named keys to retrieve the value.

For example, now we assign price for each fruit of above php array, we use fruit as array key, and the value is price, to retrieve the price we us the fruit name as key of array element.

$fprice = array("Banana=>10", "Apple=>15", "Papaya=>50", "Grape=>25");

// We also can asssign price like below 

// To retrieve value from array we can use key name.
echo $fruits["Grape"];

Multidimensional arrays in php, Array that contain one or more array elements.

To understand multidimensional array in php, we need to understand row and column concept, just like table structure.

Now we take the above fruit array example, and add one column "earlier price", that means for each fruit, we want to store current price and earlier price.


 $fruits = array (
Retrieve value from php array

To retrieve both prices of any fruit from above array, we have to use index number like example below.


    echo $fruits[0][0]; 
    echo $fruits[1][0]; 
    echo $fruits[2][0]; 
    echo $fruits[3][0]; 

    echo $fruits[0][1]; 
    echo $fruits[1][1]; 
    echo $fruits[2][1]; 
    echo $fruits[3][1];


To learn more about array data structure in different programming language, you can look at following examples.

PHP Array Example
Learn php programming, php web development with free tutorials
Other Popular Tutorials
PHP Examples | Join PHP Online Course