How to test which HTML form button was pressed in PHP

execImagine you have a HTML form with several values and two buttons at the bottom. One could say “Do This” and the other “Do That”. How do you know which one was pressed by the user?

It’s fairly easy – but I keep forgetting this time and time again. We do this by accessing the name attribute of the HTML button in PHP.

Consider this HTML form:

The button classes are WordPress standard “blue” and “grey” button layouts, and the value is what’s written on the button. The secret sauce however is in the name fields here.

Back in PHP when the form is submitted we can access the $_POST variable which an array of values we’re getting back from the form. We can access them like this:

You can access the rest of your form’s elements in the same way (i.e. tick boxes, select options, text fields, etc).

About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs several YouTube channels and websites, and he's also live on Twitch sometimes. To support him on his mission to make the world a better place, you can support him on Patreon or buy him a coffee.

Add your voice!