How to Create an Associative Array in PHP 


               


How to Create an Associative Array in PHP

php



How to Create an Associative Array in PHP

To create an associate array in PHP, we can either create it all using one statement or we can do it in multiple statements.

One Statement

To create an associative array all in one statement, we must declare and initialize the values of the array all on one line.

We do this by the following general format:

$array_name= array('key1' => 'value1, 'key2' => 'value2', 'key3' => 'value3');

Examples

Integer Assignment

$telephone_extensions= array('John' => 345, 'Lisa' => 678, 'Terry' => 456);

String Assignment

$Eye_color= array ('George' => 'Brown', 'Mary' => 'Blue', 'Marie' => 'Green');

Multiple Statements

To create an associative array in multiple lines, we first declare the array and then we assign values to each element using separate lines.

The format to create an associative array using multiple lines is:

array_name= array();
array_name['key1']= value1;
array_name['key2']= value2;
array_name['key3']= value3;


Examples

Integer Assignment

$telephone_extensions= array();
$telephone_extensions['John']= 345;
$telephone_extensions['Lisa']= 678;
$telephone_extensions['Terry']= 456;


String Assignment

$Eye_color= array();
$Eye_color['George']= 'Brown';
$Eye_color['Mary']= 'Blue';
$Eye_color['Marie']= 'Green';

As seen in the examples, when assigning a string value to an element in an array, we must enclose the string in single quotes (' '). When assigning an integer value, we use no quotes at all.

Actual PHP Output

John: 345
Lisa: 678
Terry: 456

George: Brown
Mary: Blue
Marie: Green


HTML Comment Box is loading comments...