PHP Associative Array - php forum - Phptpoint.com

PHP Associative Array

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

/ins>

Associative array PHP

In associative array index( key ) can initialized according to Your own requirement.

An array in PHP is actually an ordered map. A map is a type that associates values to keys.

In this association use ( => ) sign to define index and values.
Associative arrays can not follow any types of order.

There are two ways to create an associative array

First Way to define associative Array

Output
Ravi is 30 Years old

In the above example
This is first way to create associative array. We create an array and store in( $Personage).
here the key(index) is user defined, numerical key is not always best way to do it. Inside echo statement ($Personage[“Ravi”]) is used to fetch the age of ravi.
In this program “Ravi” is act as index/key of an array.

Another Way to define associative Array

Output
Harmeet is 43 Years old

This is the second way to create an associative array. Value assign to an array each Line. This method is long So we use Previous method.


Loop Through an Associative Array

To loop through and print all the values of an associative array, you must use a foreach loop

Output
Delhi Haryana Punjab Bihar

In the above example
foreach loop is used to loop through arrays
Defined an associative Array variable ($state) states are defined inside the array. Foreach loop is used.
the value of the current array element is assigned to $val . Print the value of elements of array.

Using foreach display index(key) value of $state array

Output
Dl — Delhi
Hr — Haryana
Pn — Punjab
Br — Bihar

Keep Updating yourself