How to get current key in foreach in pl/pgsql?

arrays, foreach, loops, plpgsql, postgresql

Solution

`FOREACH` is meant for looping through the elements of an array value, not through their keys. `FOR` or `generate_subscripts()` can be used for that.

But generally, there should be no relation between the array's key and value.

Problem

I iterate over an array, and do something with both the array value and its key. Since PostgreSQL 9.1 there is foreach loop, so the array value is no problem, but is there any elegant way to get the key? The only solution I found is to maintain extra variable for this: ``` CREATE OR REPLACE FUNCTION foobar( bar integer[] ) RETURNS integer AS $$ DECLARE foo integer; barkey integer; BEGIN barkey := 1; FOREACH foo IN ARRAY bar LOOP -- do some stuff using foo and barkey barkey := barkey + 1; END LOOP; END; $$ LANGUAGE plpgsql; ``` Is this the best solution, or is there something more elegant?

Original source