You can use php to dynamically write javascript yes (just like you can use PHP to write html)... and that's what you'd have to do. You still need to keep in mind that your button click action is still purely javascript because the PHP is parsed before it is sent to the browser. So you'd have to use the pHP to dynamically create your JS functins.
You need to look in JS forums for event handlers such as onclick to see how the JS needs to be coded, and then work backwards from that to write the PHP...