quick php efficiency tip

Rewrote some code today. It was a bit long-winded.

It was:

 $name=getVar('name');
 $id=getVar('id');
 $start=getVar('start');
 $action=getVar('action');

Rewrote to:

 foreach(array('name','id','start','action') as $v)$$v=getVar($v);

This method can be used to really help clean up longwinded variable initialisations.

9 Comments.

  1. You know its entries like this can really make a blog. Its something that I myself do; its soemthing very simple; its something that a lot of experienced coders do and that some experienced people really should be doing yet aren’t; and yet its mentioned practically nowhere on the web. Its only drawback would be readability, but its not that hard even for a novice to figure out. Its just a pity you had to post those coffee musings beforehand 🙂

  2. yeah – it’s difficult, sometimes, to justify posting a whole article for just one tip, though. And, you’re right – it’s something which should be obvious for any near-competent programmer. Surprisingly, though, I’ve been coding in PHP since the 20th century, and I never thought to do this.

    Makes you wonder, really – 1) how many other simple tricks have passed me by? 2) they let me write programs without knowing these things? 🙂

  3. Sweet! I gotta read more! That is going to be so handy. Thanks for going where some of us don’t Kae!

  4. Yeah $$ is very useful because php with eval it at runtime meaning you can do quite funky things if the application of it is correct.

    For example.
    ($this->_my_function_prefix.$keyword)($args);
    }
    private function my_func_test($args) {
    print_r($args);
    }
    }
    $myclass = new my_class();
    $myclass->my_handler(“test”, array(“arg1”, “arg2”, “arg3”); //etc
    ?>

    I’m not sure how useful or relevant this is to this particular article, but you were saying how you had posted just for one tip i thought i might try add some more!

  5. Argh, i think i broke your page!

  6. Jay – lol! it’s wordpress – doesn’t like left pointy brackets. try putting them in as &lt; (renders as <)

  7. quick php efficiency tip ” klog « SirViejo - pingback on November 27, 2009 at 6:49 pm
  8. Asignacion dinamica de variables en php « SirViejo - pingback on November 27, 2009 at 10:34 pm
  9. Asignacion dinamica de variables en php « SirViejo - pingback on December 3, 2009 at 4:40 pm

Trackbacks and Pingbacks:

%d bloggers like this: