Thank you, but shouldn't I better use FOREACH for my task?
SQL based solution (functional based) solution can be faster and shorter. PLpgSQL is nice language, but what you can do about arrays functionally, you should to do :). Usually it is significantly faster.
But, you can try - it is good example for learning, try to implement it different ways and compare speed.