00 Votes

PHP: Loop through associative Array with Key and Foreach

Question by Guest | 2015-07-01 at 16:15

You can simply go through a complete array in PHP by just writing "foreach ($arr as $value)" in order to get all values of the array $arr in the variable $value within a loop.

But what about associative arrays, arrays consisting of key-value-pairs? I can also handle those arrays with foreach, but, however, I only get the value and not the corresponding key.

How is it possible to loop through an associative array in PHP with the help of foreach and to get both, key and value within the loop?

ReplyPositiveNegative
0Best Answer0 Votes

Here is an example of how to loop through an associative array with keys and values using foreach:

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

foreach ($arr as $key => $value) {
   echo "Key = $key, Value = $value";
   echo '<br>';
}

First of all, we are creating an associative array containing the keys "A" and "B" and the values 100 and 200. After that, we are using a foreach loop to output the values and keys.

Instead of writing "$arr as $value" we are using "$arr as $key => $value" which makes us getting the key in the variable $key and the value in the variable $value.
2015-07-02 at 23:20

ReplyPositive Negative
Reply

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.

Participate

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