PHP's $$, or Variable Variable Name

One of the things I've found incredibly helpful in PHP development is the variable variable, or $$. I'm not sure where or when I discovered this, but it's an incredibly helpful shortcut and can actually help you avoid some dumb mistakes from typos, etc.

One really good use-case I've found is when you're processing form data. Using variable variable names can save you a ton of redundant work by simply looping through the $_POST or $_GET arrays and setting the variable name to the form field name.

Let's say we're submitting the following form:

<form name="contact" method="post" action="/path/to/php/script.php">
    <input type="text" name="name" placeholder="name" required />
    <input type="tel" name="phone" placeholder="phone number" />
    <input type="email" name="email" placeholder="email address" required />
    <input type="text" name="address" placeholder="mailing address" />
    <input type="url" name="url" placeholder="url" />
    <input type="submit" id="submit" value="send" />
</form>

The long way

<?php
    $form = $_POST;
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];
    $email = $_POST['email'];
    $url = $_POST['url'];
    // then you have to do something with those variables.. 
    // and so on.. 
?>

Using $$

<?php
    $form = $_POST;
    for each ($form as $key=>$value) {
        $$key = $value;
    }

    // Now you can access form fields names as $name, $phone, etc
    // or whatever the key names were in the $_POST array
?>

Obviously the time savings here isn't tremendous with a short form like this, but this can really reduce a lot of redundant work with longer forms—or in plenty of other uses when you have to assign variable names to existing key/value pairs.

Add new comment