PHP Create Associative Arrays
In this chapter you will learn:
- What is a PHP Associative Array
- Syntax to create PHP Associative Array
- Example of a PHP Associative Array
- 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:
- What is PHP Array Operator
- Syntax for array operator []
- Example to use PHP Array Operator
- Example - Create Associative Arrays with Array Operator
Home » PHP Tutorial » PHP Array