Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Option A)</p> <pre><code>&lt;?php function registerTemplateA() { // loop over every variable defined in the global scope, // such as those you created there when calling this function foreach($GLOBALS as $potentialKey =&gt; $potentialValue) { $valueArgs = func_get_args(); if (in_array($potentialValue, $valueArgs)) { // this variable seems to match a _value_ you passed in $args[$potentialKey] = $potentialValue; } } // you now have an associative array in $args print_r($args); } registerTemplateA($name = "my template", $screenshot = "screenshot.png", $description = "nice template"); ?&gt; </code></pre> <p>Option B)</p> <pre><code>&lt;?php function registerTemplateB() { // passing in keys as args this time so we don't need to access global scope for ($i = 0; $i &lt; func_num_args(); $i++) { // run following code on even args // (the even args are numbered as odd since it counts from zero) // `% 2` is a modulus operation (calculating remainder when dividing by 2) if ($i % 2 != 0) { $key = func_get_arg($i - 1); $value = func_get_arg($i); // join odd and even args together as key/value pairs $args[$key] = $value; } } // you now have an associative array in $args print_r($args); } registerTemplateB('name', 'my template', 'screenshot', 'screenshot.png', 'description', 'nice template'); ?&gt; </code></pre> <p>Option C)</p> <pre><code>&lt;?php function registerTemplateC($args) { // you now have an associative array in $args print_r($args); } registerTemplateC(array('name' =&gt; 'my template', 'screenshot' =&gt; 'screenshot.png', 'description' =&gt; 'nice template')); ?&gt; </code></pre> <p>Conclusion: option C is the best "for minimum code"</p> <p>(Note: this answer is valid PHP code, with open and close tags in the correct places, tested using PHP 5.2.x and should run on PHP 4 also... so give it a try if you must.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload