PHP

PHP Associative Arrays

Associative arrays are very similar to numeric arrays in terms of functionality but they are different in terms of their index method.

Key-Value Pair

Associative array will have their index as string so that you can establish a strong association with between key and values.
Associative elements are passed in the format "key" => "value".

Associative arrays are arrays that use named keys (index) that you assign to them.

Syntax:

In PHP, There are two ways to create an associative array:

$var = array("key1"=>"Value1", "key2"=>"Value2", "keyN"=>"ValueN");

//or
$var['key1'] = "Value1";
$var['key2'] = "Value2";
$var['keyN'] = "ValueN";

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 key (index) and values.
Associative arrays can not follow any types of order.

Example:

<?php
    $marks = array("Maths"=>"85", "Science"=>"89", "English"=>"78");
    echo "Obtained Marks in Maths = ".$marks['Maths'];
?>

This is first way to create associative array. We create an array and store in $marks.
Here the key (index) is user defined, Inside echo statement $marks['Maths'] is used to fetch the Marks associated with key Maths.
In this program "Maths" is act as key (index) of an array, and it also called named key.

Output:

Tutorialik.com
Obtained Marks in Maths = 85

Example:

<?php
    $marks['Maths'] = "85";
    $marks['Science'] = "89";
    $marks['English'] = "78";
    echo "Obtained Marks in Maths = ".$marks['Maths'];
?>

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.

Output:

Tutorialik.com
Obtained Marks in Maths = 85

Using foreach statement to go through individual element

To go through individual element of an associative array, you could use foreach loop.

foreach:

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

Example:

<?php
    $marks = array("Maths"=>"85", "Science"=>"89", "English"=>"78");
    foreach($marks as $mark) {
        echo "$mark ";
    }
?>

Output:

Tutorialik.com
85 89 78
 

Above example is not clear, as we only got mark (value) not subject (key). So it is difficult to say which mark associated with witch subject!
if you want to get both key and value, follow example below.

Example:

<?php
    $marks = array("Maths"=>"85", "Science"=>"89", "English"=>"78");
    foreach($marks as $key=>$value) {
        echo "Subject = " . $key . ", Mark = " . $value;
        echo "<br />";
    }
?>

Output:

Tutorialik.com
Subject = Maths, Mark = 85
Subject = Science, Mark = 89
Subject = English, Mark = 78



Subscribe us on Youtube

Share This Page on


Ask Question