Home »
PHP »
PHP programs
Create an associative array in PHP
Learn, what is an associative array and how to create an associative array in PHP?
Submitted by IncludeHelp, on February 07, 2019 [Last updated : March 13, 2023]
PHP - Associative Array
In an associative array, we can specify the values with the keys. Then, following two things are required to create an associative array: 1) key, and 2) value
key can be used as an index to access the value from the array.
Note: To create an associative or other types of array, we use array() function.
Syntax
array(key1=>value1, key2=>value2, key3=>value3, ...);
PHP code to create an associative array
In this example, we are creating an associative array, printing the values: 1) Using keys, and 2) Printing complete array with keys & values
<?php
//creating student array with keys & values
$std = array('id' => "101", 'name' => "Amit", 'course' => "B.Tech");
//printing elemenets
print ("std elements...\n");
print ("Id = " . $std['id'] . " Name = " . $std['name'] . " Course = " . $std['course']);
//printing array using for each loop
//printing complete array
print ("std...\n");
print_r($std);
?>
Output
std elements...
Id = 101 Name = Amit Course = B.Techstd...
Array
(
[id] => 101
[name] => Amit
[course] => B.Tech
)
PHP Array Programs »