PHP Create Associative Arrays

Definition

PHP Associative Arrays are array with your own keys.

Syntax

We can use array() function to create associative array.


$myarray = array("key1"=>"value1", "key2"=>"value2", ....); 

Example

The following code creates a PHP associative array to hold the key value pair.


<?PHP
$myarray = array("a"=>"Apple", "b"=>"Bag", "c"=>"Cat"); 
var_dump($myarray); 
?>

The code above generates the following result.

PHP converts floating-point numbers to integers in the associative arrays, which essentially rounds them down.

Example 2

The following PHP code creates an Associative Array with different type of values.


<?PHP//from www  .j  a  va  2s  .  c  om
$myBook = array( "title" =>  "Learn PHP from java2s.com", 
                 "author" =>  "java2s.com", 
                 "pubYear" =>  2000 );   

?>

This creates an array with three elements:

  • "Learn PHP from java2s.com" , which has an index of "title";
  • "java2s.com", which has an index of "author";
  • and 2000 , which has an index of "pubYear".




















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone