PHP Associative Array

PHPServer Side ProgrammingProgramming

Definition and Usage

In PHP, an array is a comma separated collection of key => value pairs. Such an array is called Associative Array where value is associated to a unique key. The key part has to ba a string or integer, whereas value can be of any type, even another array.

Use of key is optional. If array consists only of values, it becomes an indexed array, with zero based positional index of value behaves as a key.

Array object can be initialized by array() function as well as assignment by putting elements inside square brackets []

Syntax

//Associative array using array() function
$arr=array(key1=>val1, key2=>val2,key3=val3,..);
//Associative array using assignment method
$arr=[key1=>val1, key2=>val2,key3=val3,..];

Key should either be integer or string. Value component can be of any PHP type. If a certain key appears repeatedly, last value assigned will overwrite earlier values. We can access value associated with a certain key by following syntax −

$arr[key1];

PHP Version

Use of square brackets for assignment of array is available since PHP 5.4

Following example uses array() function to declare an associative array

Example

 Live Demo

<?php
$arr=array(1=>"one", 2=>"two", 3=>"three");
var_dump($arr);
?>

Output

This will produce following result −

array(3) {
   [1]=>
   int(11)
   [2]=>
   int(22)
   [3]=>
   int(33)
}

This Example uses square brackets for assignment of associative array

Example

 Live Demo

<?php
$arr=[1=>"one", 2=>"two", 3=>"three"];
var_dump($arr);
?>

Output

This will produce following result −

array(3) {
   [1]=>
   string(3) "one"
   [2]=>
   string(3) "two"
   [3]=>
   string(5) "three"
}

We can traverse the array elements using foreach loop as follows:

Example

 Live Demo

<?php
$arr=[1=>"one", 2=>"two", 3=>"three"];
//using foreach loop
foreach ($arr as $key=>$value){
   echo $key . "=>" . $value . "\n";
}
?>

Output

This will produce following result −

1=>one
2=>two
3=>three

This Example shows modify value of existing element and add new key-value pair using square brackets

Example

 Live Demo

<?php
$arr=[1=>"one", 2=>"two", 3=>"three"];
//modify array element
$arr[2]="twenty";
//add new element in array
$arr[10]="ten";
//using foreach loop
foreach ($arr as $key=>$value){
   echo $key . "=>" . $value . "\n";
}
?>

Output

This will produce following result −

1=>one
2=>twenty
3=>three
10=>ten
raja
Published on 19-Sep-2020 17:52:11
Advertisements