Nurasto.com Website

My digital scrapbook

PHP Trick to generate variables from FORM

on under Software and Web DevelopmentBe the first to comment

I hate to write code, really! hehehe … I often hand-code my code, even in Visual Studio! Heck, I don’t know why I love this style of coding. The one that I don’t code is when approching Database, I often use tools to help me generate code, just say PHPMyAdmin.

Sometime, I hate to write code especially when dealing with something called “Form Gathering” with any method like GET/POST. If I handle only one to six data, I will write it happlily ever after. I was create a webform consisting 27 inputs, yeah, 27 inputs. I assume you understand about HTML Form.

PHP is very handy programming engine and I love to make a shortcut to deal with those 27 inputs. I create a code which gathering all inputs and my PHP code create another code.

This is the code :

<?php
foreach($_POST as $key => $value) {
  echo $key.' = $_POST["'.$key.'"]; <br />';
}
?>

I don’t like escaping too much so I use echo and concation operator (the dot). So what the code doing?

  • $_POST is an array and contain collections of element in form. So, we could create loop to access the individual item. If you use GET method, please change the $_POST into $_GET.
  • You may be wondering why I create $value variable which I never be use. The reason is very simple, I just want to know the “name” of form elements (input) not the value.
  • Echoing the the line to create a new code that I could copy paste into another PHP File.

Creating little tool like this often help developer increase his/her productivity. Why? because you can reuse it for next projects.

Happy Programming with PHP!.