11 Vote

PHP: How to create Array with Key Value Pairs?

Question by Guest | 2015-07-05 at 00:35

Up to now, I have often seen so-called associative arrays in PHP which are arrays that can not only be accessed via an index, but also by using a key word or key.

For example, some MySQL functions in PHP are creating such arrays, so that you can simply access the result array via the column names of the respective table.

But how is it possible to create such an associative array containing own key-value-pairs in my own PHP code? When creating an array using $arr = array('A', 'B', 'C'), I always get the default array with a normal numerical index.

1Best Answer1 Vote

You can create an associative array in PHP in the following way:

$arr = array();
$arr['A'] = 100;
$arr['B'] = 200;

In this example, we are setting the key "A" to 100 and the key "B" to 200.

Alternatively, we can use the following syntax, the result is the same:

$arr = array('A' => 100, 'B' => 200);

After that, we can access the values for example in this way:

echo $arr['A'];
$k = $arr['B'] + 20;
echo $k;

How to loop through an associative array with foreach, you can read in the topic about how to go through a key value array using foreach.
2015-07-06 at 22:42

ReplyPositive Negative

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.