Friday, July 1, 2011

PHP concat variable name with str/string

In PHP, concatenate variable names with strings by using curly brackets {}.

The Shorter version
<?php
       // setting every $nvar* to ":)"
       $nameArray = array("Alice", "Bob", "Charlie");
       foreach ($nameArray as $name) {
           ${ "nvar" . $name } = ":)"; 
       }
?>

and

The Longer version
<?php
       // setting every $nvar* to ":)"
       $nameArray = array("Alice", "Bob", "Charlie");
       foreach ($nameArray as $name) {
           $nameVar = "nvar" . $name;
           ${ $nameVar } = ":)"; 
       }   
?>

are the same as

The Brute-force version
<?php
       // setting every $nvar* to ":)"
       $nvarAlice = ":)";
       $nvarBob = ":)";
       $nvarCharlie = ":)";
?>

Read documentations here.

No comments:

Post a Comment