In PHP, Associative arrays are key and value pairs. where key is any user defined string and value can be of any data type. These keys are used to access values in associative arrays.

Syntax

array_name = array("key"=>value, "key"=>value, "key"=>value);
Keyis used to access value.
Valueis the data, which key holds in associative array.

Create an Associative array

<?php
     // Create an Associative array
     $student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");
?>

Associative array is created using array() function with key=value pairs.

Above example, has $student array variable which holds three key-value pairs, which are explained in below table.

KeyValue
nameVasu
age17
class12th

Access Associative arrays

Associative array can be accessed in two ways

  1. Traversing through loop
  2. with Key directly

Traversing through loop

Access key value

<?php
	$student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");

       foreach ($student as $k => $v) {
  		echo "$k : $v <br>";
	}
?>

Access only Key

<?php
       $student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");

       foreach ($student as  $k => $v) {
  		echo " $k <br>";
	}
?>

Example explained

$studentIs an associative array
$kRepresents all keys in $student array
$vRepresents all related key and its value in $student array

using array_keys() function

<?php
      $student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");

      $keys = array_keys($student);
      foreach ($keys as $k) {
   	 echo $k;
      }
?>

Access only value

<?php
	$student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");

       foreach ($student as $v) {
  		echo " $v <br>";
	}
?>

2) With Key directly

Individual key can be used to accessed value of a particular key in associative array.

<?php
	$student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");
        echo $student["name"] . "<br/>";
        echo $student["age"] . "<br/>";
        echo $student["class"] . "<br/>";
?>

Using for loop

<?php
	// Create an associative array
	$student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");

        $keys = array_keys($student);

	for($i=0; $i < count($keys); $i++) {
		echo $keys[$i] . ' ' . $student[$keys[$i]] . "\n";
       }
?>