In the first place, there are cell phone viruses. These viruses spread through internet, bluetooth or MMS.
However, in your case it doesn't sound like a virus, but more like a problem with the keypad of your phone. The most likely cause is that you got it wet one time. The 'switches' in the keypad start to short out partially, and your phone starts doing funny things. After a while when most water is gone, the phone starts functioning again. Until the switches are corroded enough that the buttons won't work at all anymore.