Associative Array in PHP?

Posted by

An associative array is a simple and very important array of PHP. This array is also used the most, it is very easy to understand this array, and it contains keys and values. In simple Hindi language, key works like name and value work as information related to that name. For Mohan is a key and Mohan’s age or address, email, etc are its values.

With the help of an associative array, you can assign any value to any key. Associative array depends on key and value (=>).

An associative array is the best array in PHP. An associative array is used to store key => value pair. We define a key for value. At the time of execution (at run time), we can get the value related to the key by using the key.

PHP Associative Array Syntax

$x = array('key1'=>'value1', 'key2'=>'value2');
$x = ['key1'=>'value1', 'key2'=>'value2'];

Difference Between Indexed Array And Associative Array

The biggest difference between an Indexed Array and an Associative Array in PHP is that in an Indexed Array we only have to insert values so that value is associated (bind) with an indexed number, whereas in an Associative Array we insert value with a key so that The value is associated only with the given key.

Example:-

<?php
    $age = array (
        "Ajay"=>10,
        "Vijay"=>20,
        "Sanjay"=>30,
    );
    echo $age["Ajay"] . "<br>";
    echo $age["Vijay"] . "<br>";
    echo $age["Sanjay"] . "<br>";
?>

Output:-

Associative arrays are written in two ways.

Type 1 :

<?php
    $percentages = array(
                     "Raj" => 54, 
                     "Prakash" => 85, 
                     "Narayan" => 60 
    );

    echo "Raj got ".$percentages["Raj"]. " percentages. <br />";
    echo "Prakash got ".$percentages["Prakash"]. " percentages. <br />";
    echo "Narayan got ".$percentages["Narayan"]. " percentages. <br />";
?>

Output:-

Type 2 :

<?php
    $percentages["Raj"] = 54; 
    $percentages["Prakash"] = 85;
    $percentages["Narayan"] = 60;

    echo "Raj got ".$percentages["Raj"]. " percentages. <br />";
    echo "Prakash got ".$percentages["Prakash"]. " percentages. <br />";
    echo "Narayan got ".$percentages["Narayan"]. " percentages. <br />";
?>

Output:-

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x