How to Add Key & Value in Array in PHP

Key value pairs in PHP known as associative arrays.  Example is given below where we are adding more items to the previously initialized associative array.

<?php

//Creating Associative Array.
$array = array(
    "Robert" => "USA",
    "Peter" => "UK",
);

echo "Before Addition Array Length: ". count($array)."<br />";

//Adding more items to Associative Array;
$array["Mike"] = "Canada";
$array["John"] = "Africa";

echo "After Addition Array Length: ". count($array)."<br />";

echo $array["Mike"];


?>

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •