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?
Related Topics
Send Form Input as an Array to PHP Script
Tip | 0 Comments
JavaScript: Create and Use Arrays
Info | 0 Comments
PHP: Remove all empty elements from string array
Tip | 0 Comments
PHP: Save MySQL Result in Array
Info | 0 Comments
Lazarus: Load File as Byte Array and save Byte Array as File
Tutorial | 0 Comments
PHP: Write array to individual Variables
Tutorial | 0 Comments
PHP: Fill Array with Sequence of Numbers or Characters
Tutorial | 0 Comments
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.
Here is an example of how to loop through an associative array with keys and values using foreach:
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