PHP Create Associative Arrays

In this chapter you will learn:

  1. What is a PHP Associative Array
  2. Syntax to create PHP Associative Array
  3. Example of a PHP Associative Array
  4. Example - Create Associative Array with different type of values

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//  j av a 2s .  co m
$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".

Next chapter...

What you will learn in the next chapter:

  1. What is PHP Array Operator
  2. Syntax for array operator []
  3. Example to use PHP Array Operator
  4. Example - Create Associative Arrays with Array Operator
Home » PHP Tutorial » PHP Array
PHP Array
PHP Create Indexed Array
PHP Create Associative Arrays
PHP Array Operator
PHP Access Array Element
PHP Change Array Element
PHP Create Array using Square Bracket
PHP Array Element Loop Through
PHP Array foreach loop
PHP Change Array Values with foreach
PHP Array Multidimensional
PHP Access Element in Multidimensional Array
PHP Loop Through Multidimensional Array