Simplify Form Handling in a Big Way

Simplify Form Handling in a Big Way

Tutorial Details
  • Program: PHP
  • Difficulty: Intermediate
  • Estimated Completion Time: 45 minutes

Save time, reduce maintenance pains, simplify your code, and do it all while feeling like a freakin’ genius! In this tutorial, learn how to use variable variables, lookup arrays, and a bit of clever programming to simplify form handling in a big way.


Variable Variables, Methods, and Properties

Before we can get too deep into using a lookup array, it’s important to first understand the concept behind variable variables.

What Are Variable Variables?

Variable variable is a term, which describes the use of a variable to declare another variable.

In the simplest form, a variable variable might look like:

$foo = 'A value!'; // Declare an initial value
$bar = 'foo'; // Wait, what's happening?
echo $$bar; // Holy crap! That output 'A value!'

Why Should you Care?

When you look at a proof of concept like the previous example, using variable variables probably looks pretty silly and overcomplicated. However, there really are solid, practical reasons to use them in some cases.

Lookup arrays can easily simplify your code

Practical Examples

The responsible use of variable variables can drastically reduce the amount of code that needs to be repeated by, say, converting an associative array to an object with sanitized values.

Example without variable variables

$comment = new stdClass(); // Create an object

$comment->name = sanitize_value($array['name']);
$comment->email = sanitize_values($array['email']);
$comment->url = sanitize_values($array['url']);
$comment->comment_text = sanitize_values($array['comment_text']);

Example with variable variables

$comment = new stdClass(); // Create a new object

foreach( $array as $key=>$val )
{
    $comment->$key = sanitize_values($val);
}

See how much simpler that was? And you can imagine what the example without variable variables would look like if the array had something like 50 or 100 values.

NOTE: I’m aware that you could also use array_map() and explicitly cast the array as an object to accomplish the same thing. That’s not the point. We’re illustrating a concept, here. Play along.


The Problem with Form Processing

Make form processing a breeze.

Now that you know how to use variable variables, we can move on to the meat and potatoes of this article, which is the idea that incorporating a lookup array instead of multiple controller files or a switch statement can save you a lot of extra maintenance, repeated code, and headache in general.

To illustrate our concept, we’re going to use the idea of form processing. This is an essential aspect of web programming, and can also be one of the most tedious areas of any project.

However, after reevaluating your coding habits, you can potentially make form processing a breeze.

Frequently, either an individual file is created for each form to be processed, or a switch statement is used. In this section, we’ll go over how both solutions might be implemented, and then we’ll examine a solution using variable variables, and how it can improve your projects.

A Working Example with Multiple Form Processing Files

An often used method for handling form submissions is to create a whole new file to handle each form’s data separately.

Take, for example, these three forms that update a user account with a new name, new email, or both:

<form action="assets/inc/ex1-form1.php"
      method="post"
      id="ex1-form1">
    <div>
        <h4>Form 1</h4>
        <label>Name
            <input type="text" name="name" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

<form action="assets/inc/ex1-form2.php"
      method="post"
      id="ex1-form2">
    <div>
        <h4>Form 2</h4>
        <label>Email
            <input type="text" name="email" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

<form action="assets/inc/ex1-form3.php"
      method="post"
      id="ex1-form3">
    <div>
        <h4>Form 3</h4>
        <label>Name
            <input type="text" name="name" class="input-text" />
        </label>
        <label>Email
            <input type="text" name="email" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

Each of these forms points to a different processing file. So what does each of these files look like?

Processing form 1 (assets/inc/ex1-form1.php)

<?php

// Turn on error reporting so we can see if anything is going wrong
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Make sure our faux-token was supplied
if( isset($_POST['token']) && $_POST['token']==='secret token goes here' )
{
    // Require the necessary class
    require_once 'class.copterlabs_account.inc.php';

    // Create a new instance of the class
    $account_obj = new CopterLabs_Account();

    // Handle the form submission
    $output = $account_obj->save_name();

    // For this example, just output some data about the form submission
    echo "<pre>Processing File: ", $_SERVER['PHP_SELF'],
            "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n",
            '<p><a href="../../">Go back</a></p>';
}
else
{
    die( 'Invalid form submission' );
}

Processing form 2 (assets/inc/ex1-form2.php)

<?php

// Turn on error reporting so we can see if anything is going wrong
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Make sure our faux-token was supplied
if( isset($_POST['token']) && $_POST['token']==='secret token goes here' )
{
    // Require the necessary class
    require_once 'class.copterlabs_account.inc.php';

    // Create a new instance of the class
    $account_obj = new CopterLabs_Account();

    // Handle the form submission
    $output = $account_obj->save_email();

    // For this example, just output some data about the form submission
    echo "<pre>Processing File: ", $_SERVER['PHP_SELF'],
            "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n",
            '<p><a href="../../">Go back</a></p>';
}
else
{
    die( 'Invalid form submission' );
}

Processing form 3 (assets/inc/ex1-form3.php)

<?php

// Turn on error reporting so we can see if anything is going wrong
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Make sure our faux-token was supplied
if( isset($_POST['token']) && $_POST['token']==='secret token goes here' )
{
    // Require the necessary class
    require_once 'class.copterlabs_account.inc.php';

    // Create a new instance of the class
    $account_obj = new CopterLabs_Account();

    // Handle the form submission
    $output = $account_obj->save_both();

    // For this example, just output some data about the form submission
    echo "<pre>Processing File: ", $_SERVER['PHP_SELF'],
            "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n",
            '<p><a href="../../">Go back</a></p>';
}
else
{
    die( 'Invalid form submission' );
}

As you can plainly see, the example files above are duplicating a ton of code. Expand this to 15 forms on a site, and you’ll quickly find that maintenance could become a nightmare.

The Account Class

As you can see, the processing files are creating an instance of the class CopterLabs_Account. This will be a very simple class that outputs information about a form submission.

Here’s the code for the class (assets/inc/class.coperlabs_account.inc.php):

<?php

/**
 * A simple class to test form submissions
 *
 * PHP version 5
 *
 * LICENSE: Dual licensed under the MIT or GPL licenses.
 *
 * @author    Jason Lengstorf <jason.lengstorf@copterlabs.com>
 * @copyright 2011 Copter Labs
 * @license   http://www.opensource.org/licenses/mit-license.html
 * @license   http://www.gnu.org/licenses/gpl-3.0.txt
 */
class CopterLabs_Account
{

    public $name = NULL,
           $email = NULL;

    public function save_name()
    {
        $this->name = htmlentities($_POST['name'], ENT_QUOTES);

        return "Method: " . __METHOD__ . "\nName: " . $this->name . "\n";
    }

    public function save_email()
    {
        $this->email = htmlentities($_POST['email'], ENT_QUOTES);

        return "Method: " . __METHOD__ . "\nEmail: " . $this->email . "\n";
    }

    public function save_both()
    {
        $this->name = htmlentities($_POST['name'], ENT_QUOTES);
        $this->email = htmlentities($_POST['email'], ENT_QUOTES);

        return "Method: " . __METHOD__ . "\nName: " . $this->name . "\nEmail: "
                . $this->email . "\n";
    }

}

You can try out this code at Example 1 on the demo page.

A Working Example with a Single Processing File and a Switch Statement

Another popular solution for form processing is to consolidate all the processing scripts into one file and determine what to do with the data using a switch statement.

The switch approach commonly employs a trick in which a hidden input is added to the form containing an action to be taken upon submission. This
action is then used to determine what to do with the form.

Here are the same three forms, from above, with actions added, all pointing to a single processing file:

<form action="assets/inc/ex2-switch.php"
      method="post"
      id="ex2-form1">
    <div>
        <h4>Form 1</h4>
        <label>Name
            <input type="text" name="name" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="action" value="update-name" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

<form action="assets/inc/ex2-switch.php"
      method="post"
      id="ex2-form2">
    <div>
        <h4>Form 2</h4>
        <label>Email
            <input type="text" name="email" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="action" value="update-email" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

<form action="assets/inc/ex2-switch.php"
      method="post"
      id="ex2-form3">
    <div>
        <h4>Form 3</h4>
        <label>Name
            <input type="text" name="name" class="input-text" />
        </label>
        <label>Email
            <input type="text" name="email" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="action" value="update-both" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

And the new processing file looks like: (assets/inc/ex2-switch.php)

<?php

// Turn on error reporting so we can see if anything is going wrong
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Make sure our faux-token was supplied
if( isset($_POST['token']) && $_POST['token']==='secret token goes here' )
{
    // Require the necessary class
    require_once 'class.copterlabs_account.inc.php';

    // Create a new instance of the class
    $account_obj = new CopterLabs_Account();

    // Sanitize the action
    $action = htmlentities($_POST['action'], ENT_QUOTES);

    // Use the new 'action' hidden input to determine what action to call
    switch( $action )
    {
        // Form 1 handling
        case 'update-name':
            $output = $account_obj->save_name();
            break;

        // Form 2 handling
        case 'update-email':
            $output = $account_obj->save_email();
            break;

        // Form 3 handling
        case 'update-both':
            $output = $account_obj->save_both();
            break;

        // If no valid action is found, something isn't right
        default:
            die( 'Unsupported action.' );
    }

    // For this example, just output some data about the form submission
    echo "<pre>Processing File: ", $_SERVER['PHP_SELF'],
            "\nAction: ", htmlentities($_POST['action'], ENT_QUOTES),
            "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n",
            '<p><a href="../../#ex2">Go back to example 2</a></p>';
}
else
{
    die( 'Invalid form submission' );
}

You can see this in action by visiting Example 2 on the demo page. This is a marked improvement over using multiple forms, but you can see that we’re still duplicating some code.

On top of that, it’s a personal preference of mine to avoid switch statements whenever I can. This is due to the fact that switch uses loose comparisons ('a string' will trigger case 0 because a string evaluates to 0 if you convert it to an integer) and is extremely easy to turn into spaghetti code.


Fixing the Problem: Lookup Arrays and Variable Variables

As we’ve seen so far, both of the above solutions have their drawbacks, and require duplicate code. Imagine if there were a dozen or more forms on the site — not pretty.

To address this issue, we can use a concept called a lookup array, which maps the actions passed from the form to a method called on the object.

Yes, you could set the action as the method name, but that allows a bogus form submission to call any public method. Making the array a key-value pair is a small step to add a little more control without much extra work.

A Working Example with a Single Processing File and a Lookup Array

Using our knowledge of variable variables from the beginning of this tutorial, let’s modify our demo to use a lookup array.

Modify the three forms to point to a new controller file:

<form action="assets/inc/ex3-lookup-array.php"
      method="post"
      id="ex3-form1">
    <div>
        <h4>Form 1</h4>
        <label>Name
            <input type="text" name="name" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="action" value="update-name" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

<form action="assets/inc/ex3-lookup-array.php"
      method="post"
      id="ex3-form2">
    <div>
        <h4>Form 2</h4>
        <label>Email
            <input type="text" name="email" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="action" value="update-email" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

<form action="assets/inc/ex3-lookup-array.php"
      method="post"
      id="ex3-form3">
    <div>
        <h4>Form 3</h4>
        <label>Name
            <input type="text" name="name" class="input-text" />
        </label>
        <label>Email
            <input type="text" name="email" class="input-text" />
        </label>
        <input type="submit" class="input-submit" value="Submit" />
        <input type="hidden" name="action" value="update-both" />
        <input type="hidden" name="token" value="secret token goes here" />
    </div>
</form>

Next, put together the processing file that will handle form submissions (assets/inc/ex3-lookup-array.php):

<?php

// Turn on error reporting so we can see if anything is going wrong
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Make sure our faux-token was supplied
if( isset($_POST['token']) && $_POST['token']==='secret token goes here' )
{
    // Require the necessary class
    require_once 'class.copterlabs_account.inc.php';

    // Create a new instance of the class
    $account_obj = new CopterLabs_Account();

    // Sanitize the action
    $action = htmlentities($_POST['action'], ENT_QUOTES);

    // Set up a lookup array to match actions to method names
    $lookup_array = array(
        'update-name' => 'save_name',
        'update-email' => 'save_email',
        'update-both' => 'save_both'
    );

    // Make sure the array key exists
    if( array_key_exists($action, $lookup_array) )
    {
        // Using variable variables, call the proper method and store the output
        $output = $account_obj->$lookup_array[$action]();
    }
    else
    {
        die( 'Unsupported action.' );
    }

    // For this example, just output some data about the form submission
    echo "<pre>Processing File: ", $_SERVER['PHP_SELF'],
            "\nAction: ", htmlentities($_POST['action'], ENT_QUOTES),
            "\n\n<strong>Method Output:</strong>\n", $output, "</pre>\n",
            '<p><a href="../../#ex3">Go back to example 3</a></p>';
}
else
{
    die( 'Invalid form submission' );
}

Check this out on the demo page by trying out the forms on Example 3.

Since we set the action as the key in the array, we use array_key_exists() to ensure that the action is valid. Then, we use the value that corresponds to the action as the method name. Notice that we added the parentheses after the value to make sure it’s executed as a method.

The addition of the lookup array keeps the code concise, simple, and clear (once you get the hang of variable variables).


Summary

Used responsibly, lookup arrays can make your scripts far easier to update and maintain when you combine them with variable variables.

How do you think you can integrate lookup arrays and variable variables into your projects to make maintenance easier? Let me know in the comments!

Tags: forms
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://rommelcastro.me Rommel Castro A.

    look like a nice article, reading right now (:

  • chria

    could use some DL files to follow through

  • http://abrightconcept.com Gabriel

    Nice article on the complexities of handling multiple forms!

    Although, I’m not sure that variable variables were used to solve it. I thought that variable variables referred to the foo-bar example in which a variable is created with a name based on it’s content, which can be dynamic. In the code used to solve the issue, the $lookup_array appears to be composed of array values that have assigned key names, rather than the usual numeric reference. These could be assigned dynamically, I believe, but in the example, they are declared and then referenced by a variable.

    Maybe I’m missing something, but I thought there was a distinction between variable variables and key references in an array that are referred to by a variable.

    Anyways, nice job, and thanks for the write-up!

    • Harold

      I’m pretty sure you’re right about this Gabriel

    • Cully Larson

      The lookup array is just used to get the function name. This variable variable then references the function that will be called on the model. So the variable variable is not the lookup in the associative array, but the function call.

  • Luca Degasperi

    Thank You! A really nice article!

  • Jonathon

    Love this concept. If you stick to consistent naming conventions you can save yourself the hassle of mapping array keys to method names.

    $foo = new Foo;
    $bar = ‘baz’;

    $foo->{$bar}(); //calls baz method from your Foo class.

    Handy if you wanted to, say, have different validation rules for different form fields. Each form element shares a name with a method from your validation class, and voila.

    • Cully Larson

      This is dangerous. As mentioned in the article, “Yes, you could set the action as the method name, but that allows a bogus form submission to call any public method. Making the array a key-value pair is a small step to add a little more control without much extra work.”

  • http://www.chimply.net Dieter

    I was using the switch case way of handling forms. :-)
    Looks much cleaner the way you’re doing it. Thanks for that! I’ll follow the comments on this article and I think I’m going to switch my switch case if they’re positive…

    I think 60-70% of my time goes to form handling and such…
    If you knew a good, clean way of saving the form-data with one function I would be really interested. The way I tried doing that is by flattening the $_POST array into a textstring and save everything as a single value in the database. When I need the data again I transform the text back into an associative array…
    The downside is that I cannot easily do sql queries on the values and that it’s really ugly code…
    Any better ideas on that subject?

    Thanks Jason!

  • http://www.gstaltig.ch Tim

    Hi there

    Hi Jason. I’d be carefull with using this in a productive environment:
    foreach( $array as $key=>$val )
    {
    $comment->$key = sanitize_values($val);
    }
    Because the $key is taken from the input name without further validation, this would grant a user a straight access to your database. Providing uid=’15′ could override the internal Database Uid of another user and so on… see where that leads?

    If I’m not using a framework I tend to declare all class properties protected and use getter/setter functions in combination with a whitelist (or a hash of all input fields as the secret token). The lookup array you use for the method calls is a perfect example of a whitelist.

    Besides this, nice tutorial offering a good starting point into oo form handling. Keep the good stuff roling.

    • alex

      Tim,

      Do you know of any tuts where I can learn more about whitelists?

      Thanks.

  • Andrew Jenkins

    Um I think your initial variable variable example doesn’t actually contain a variable variable.

    $comment = new stdClass(); // Create a new object

    foreach( $array as $key=>$val )
    {
    $comment->$key = sanitize_values($val);
    }

    • http://www.copterlabs.com/ Jason Lengstorf
      Author

      You’re absolutely right. That heading should have read “with variable methods” instead.

      Thanks for pointing that out!

  • http://www.kallmandevelopment.com Joel

    @Dieter – You asked about an easier way to handle form submissions and inserting the data into the database. I would NOT serialize or json_encode your POST array because then when you want to query based on a specific piece of that information in that string you will not be able to easily access it.

    So lets say you have a database named “users” with the fields “users_id”, “first_name”, “last_name”.

    Your form should have each input name as follows: “users[users_id]“, “users[first_name]“, “users[last_name]”

    Your $_POST will then = array(‘users’ => array(
    ‘users_id’ => ‘Entered Data’,
    ‘first_name’ => ‘Entered Data’,
    ‘last_name’ => ‘Entered Data’, ));

    Then just do a foreach($_POST as $k => $v):

    if($k===’users’)
    {
    // Run your insert with the full users data “$v”
    $this->db->insert($k, $v); // CodeIgniter Active Record Insert Function (table, data)
    }

    endforeach;

    HOPE THAT HELPS! Beware of your Submit Buttons. They’ll also be added into your $_POST array.
    Oh and use CodeIgniter. It’ll make your life easier

  • http://www.shiftedwork.de/blog Daniel S

    Hm, still not the very best solution. Thats not the right OOP way, a better way would be something like that:

    $user = User::getByID($user_id);
    $user->name = sanitize($_POST['name']);
    User::save($user);

    This requires the use of __get and __set, very useful magic methods.

    • http://www.emmyweb.com Dhruv Kumar S

      Or even better,

      $user = User::get($user_id);
      $user->name = $_POST['name'];
      $user->email = $_POST['email'];
      $user->website = $_POST['website'];

      $user->save();

      And then let the save function sanitize all the values/data.

      • http://www.murmp.com Jonathon

        Exactly, and you don’t need any switch statements. The getters and setters can determine if the values actually changes and take the appropriate action. Just set all of the elements each time and your logic simplifies even further.

      • http://aellis.me Andrew Ellis

        You can still loop with variables and take advantage of __get and __set.

        $user = User::get($user_id);
        foreach ($_POST as $key => $value)
        {
        $user->$key = $value;
        }
        $user->save();

        Then it would be up to your __set method to determine if that object has that key as an available object variable.

        Regards,
        Andrew

      • http://www.shiftedwork.de/blog Daniel S

        Hehe, the sanitize-function is for example purpose only. You can do it once more better, like that:

        $user = User::get();
        $user->update($_POST); // update() will sanitize data, too
        $user->save();

  • http://youssefboubdir.me.gp Youssef Boubdir

    Great article/concept, thank you!

  • http://graphicarmory.com Matthew Simmons

    Forms are by far my least favorite part of web design! I’m terrible at them (I can make them work perfectly, I just mess up a lot along the way). So, I take every chance to read more about them.

    Thanks for this!

  • Bastian

    Nice article. But ever since I started to develop with symfony, forms are something I don’t even have to worry anymore. The sfForm API is great and it ties very well with ORMs such as Doctrine and Propel.

    here is an example form:

    In the controller:

    In the view:

    <form action="” method=”post”>

    Process form submission:

    bind($request->getParameter($form->getName()));

    if ($form->isValid()) {
    $article = $form->save();
    }

    ?>

    You can also merge several forms together and this same work flow will work perfectly.

  • Bastian

    The above comment is broken. Upon submiting the form, it stripped all my php sample code. Trying again:

    In the controller:

    $form = new ArticleForm();

    In the view:

    <form action="” method=”post”>

    Process form submission:

    $form = new ArticleForm();
    $form->bind($request->getParameter($form->getName()));

    if ($form->isValid()) {
    $article = $form->save();
    }

  • Bastian

    Hey nettuts+! sorry this is not working. I failed to read I had to manually replace entities in my post (Why isn’t it taken care server side?) anyway, trying last time:

    In the controller:

    $form = new ArticleForm();

    In the view:

    <form action=”<?= url_for(‘article_create’) ?>” method=”post”>
    <?= $form ?>
    <input type=”submit” name=”submit” value=”Create Article” />
    </form>

    Process form submission:

    $form = new ArticleForm();
    $form->bind($request->getParameter($form->getName()));

    if ($form->isValid()) {
    $article = $form->save();
    }

  • Sam Smith

    Beautiful timing on this post.

    I’ve been working on a set of “meta” PHP scripts that generate OO class files and MySQL persistence classes. The main idea is that I can point the metascripts at a file which would be used to build a MySQL database, and the metascript will parse the SQL document and create the necessary PHP files.

    Needless to say it’s a lot of “fwrite($file, \$$variable);” stuff. Right up the alley of this article!

  • http://twitter.com/rollwiththedice Karl Ballard
    • http://www.copterlabs.com/ Jason Lengstorf
      Author

      You’re right, Karl. Originally I had it titled something ridiculously long, like “How to Use Variable Variables and Variable Methods to Simplify Form Handling in Projects.”

      Obviously, that’s not a very good title. So I shortened it and managed to make it a bit off-topic. Probably should have been “How to Use Variable Methods” instead. Thanks!

  • http://www.maughan.net.au/ Ryan Maughan

    I’ve always used:

    foreach($_POST as $variable => $value){
    $$variable = $value;
    }

    • Joshua Gdovin

      This can be done in one command. PHP offers a little item called extract that does exactly this.

      extract($_POST);

      will do the same as your sample of :

      foreach($_POST as $variable => $value) {
      $$variable = $value;
      }

      • stefgosselin

        Hey! Nice tip bro, I was also guilty of using above snippet but this is way prettier.

  • kankuro

    very nice article….. you have.. they say there are many ways how to kill a cat, trap a mouse or even solve the problems in math… as long as you derive the correct answer..

    in programming there are many approach to the problem as long as you derived the correct solution… much less code much faster…

    thanks a lot for the article… it indeed another knowledge to me and the others… god bless u always :D

  • http://www.nuresponse.com Mark

    Great NetTuts Article As usual & great comments too. Form processing seems to be continuously evolving, and I enjoy learning how others do it.

  • http://maxdegterev.name/ Max

    Well done sir! You managed to kill really good article with really bad examples!

  • http://iarmar.com Ibrahim Azhar Armar

    Well done, I learned something new, I appreciate the comments from other people trying to explain the pros and cons, I loved every bit of the article, time for me to implement in my application and reduce my code :)

  • John

    I really like this tutorial and think it will help me a lot once I’ve considered all of the implications.

    I have one question though:

    Why – in a real-world scenario – would those three separate forms be required?

    Thanks!

    — John

  • sudip

    hi jason,
    thank you for coming up with this great tutorial. It is so simple and elegant solution. But, it never striked my mind.
    I never thought to implement form processing in any of my projects in this simple way.

    Thank you, I will definitely try this approach in my next project.

  • Ian

    Hi All,

    I have been writing an application where i needed to turn a string into a variable.

    For this i needed to use variable variable which worked great, but when i wanted to use the variable variable in an array_push it wouldn’t work.

    * In the application i am looping through a directory picking out all files, each image is written category-image_name.jpg. I then needed to add each file into its appropriate array.

    Below is what i had to do:

    // Set an array to capture all bikes
    $bikes_array = array();

    // Get the file name
    $file = ‘bike-mountain_bike.jpg’;
    $file_info = pathinfo($file);

    // explode the file (category / name)
    $file_explode = explode(‘-’, $file_info['basename']);

    // Now we get the category name (bike) and use this as our array initialised above
    $file_name = $file_explode[0].’s_array’; // $bikes_array

    // We can now put our bike into the correct array
    array_push(${$file_name}, $file_explode[1]);

    I hope this helps someone.

  • http://www.bugphp.com arjun

    hi jason,
    thank you for coming up with this great tutorial

  • http://www.w3resource.com Ritwik

    This is a nice way to handle forms. Indeed variable variables has get potential.

  • Christian

    I stopped reading almost at the beginning of the tutorial, in the subject: Variable Variables, Methods, and Properties > Practical Examples, where he gives a example without variable variables and a example with variable variables, the first example “without” is true but the second example “with” is false, he’s not using any variable variables methods here, he’s just looping through an array and running a function on the value of the key in the array, so DON’T TRUST EVERYTHING IN THIS TUTORIAL, when someone is giving wrong information already at the beginning of a tutorial, then there’s a big chance for other wrong informations through the tutorial, so I haven’t even brothered to read the rest.

    If you want to learn about variable variables, then read PHP’s manual about it right here: http://php.net/manual/en/language.variables.variable.php

  • http://javahomeanddesign.com/ Tyo

    thanks for the article… can you tell me, how to make our php form more secure???
    create secure php website..

  • stef

    As others mentionned above, this is not really using dynamic variables as such, apart from in the first paragraph. Using a variable in an array key could be argued as usage of a dynamic variable, but in my humble opinion it is not quite the same as using $$var type of dynamic variables.

    Although I used to resort to using $$var type of assignment in some cases, I have been told a few times by other experienced and competent programmers that this way of assigning variables makes for harder to read code and should be avoided if possible.

    Assigning dynamic $key values to arrays is a lot more common though, and in this case thumbs up for a nice example of a practical usage case. Still a great little article, this comment ain’t meant to be a thumb-down to the author. ( Keep up the good posts. )

  • http://aykak.com Aykak

    good TUTS, but what if we use some ajax for processing of form.

  • http://stefangabos.ro/ Stefan Gabos

    Try Zebra_Form at http://stefangabos.ro/php-libraries/zebra-form/ – a PHP library for building and validating good looking forms. It has both server-side and client-side validation (the client-side validation is based on jQuery). It also does a lot of work in the background to prevent XSS hacks. See some examples at http://stefangabos.ro/wp-content/demos/Zebra_Form/

  • http://www.monclerfans.co.uk moncler

    building and validating good looking forms. It has both server-side and client-side validation (the client-side validation is based on jQuery). It also does a lot of work in the background to prevent XSS hacks. S