Based on an associative array in a Bash script, I need to iterate over it to get the key and value.
#!/bin/bash declare -A array array[foo]=bar array[bar]=foo
I actually don't understand how to get the key while using a for-in loop.
The foreach() method is used to loop through the elements in an indexed or associative array. It can also be used to iterate over objects. This allows you to run blocks of code for each element.
Bash, however, includes the ability to create associative arrays, and it treats these arrays the same as any other array. An associative array lets you create lists of key and value pairs, instead of just numbered values.
Bubble sort works by swapping the adjacent elements if they are in the wrong order. Example: Given array - (9, 7, 2, 5) After first iteration - (7, 2, 5, 9) After second iteration - (2, 5, 7, 9) and so on... In this way, the array is sorted by placing the greater element at the end of the array.
Definition and Usage In PHP, an array is a comma separated collection of key => value pairs. Such an array is called Associative Array where value is associated to a unique key. The key part has to ba a string or integer, whereas value can be of any type, even another array. Use of key is optional.
The keys are accessed using an exclamation point: ${!array[@]}
, the values are accessed using ${array[@]}
.
You can iterate over the key/value pairs like this:
for i in "${!array[@]}" do echo "key : $i" echo "value: ${array[$i]}" done
Note the use of quotes around the variable in the for
statement (plus the use of @
instead of *
). This is necessary in case any keys include spaces.
The confusion in the other answer comes from the fact that your question includes "foo" and "bar" for both the keys and the values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With