Home > Archive > PHP Language > August 2005 > Execute command from array
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Execute command from array
|
|
| Dave Thomas 2005-08-11, 5:00 pm |
| I have an array, say something like this (to build a form):
$commands = array(
"Start Date" => "build_date('startdate')",
"End Date" => "build_date('enddate')"
);
Only it will have many more entries. I want to cycle through the array,
and print the first part, but then execute the second part so that it
goes to the function build_date (which returns html code to output).
Right now I am doing it something like this:
echo "<tr><td>Start date</td><td>";
echo build_date('startdate');
echo "</td><td>End date</td><td>";
echo build_date('enddate');
echo "</td></tr>";
Because this is going to have many entries in it, it is getting very
repetitive to do it this way! I am stuck on how to execute that function
(and pass the string) with it already being a string itself.
Any ideas?
| |
| Janwillem Borleffs 2005-08-11, 5:00 pm |
| Dave Thomas wrote:
> Because this is going to have many entries in it, it is getting very
> repetitive to do it this way! I am stuck on how to execute that
> function (and pass the string) with it already being a string itself.
>
> Any ideas?
When you are able and willing to modify the array, the following might be a
solution:
$commands = array(
"Start Date" => array('build_date', array('startdate')),
"End Date" => array('build_date', array('enddate'))
);
foreach ($commands as $label => $func_args) {
print "<td>$label</td><td>";
print call_user_func_array($func_args[0], $func_args[1]);
print "</td>";
}
I have used call_user_func_array instead of call_user_func in case you want
to call functions with more then one argument.
JW
| |
| ZeldorBlat 2005-08-12, 4:00 am |
| JW has the correct solution. Another alternative is to use eval(),
but, as many have said before: "If eval is the answer, you're asking
the wrong question."
Just for kicks, here's how you could do it with eval() :
$commands = array(
"Start Date" => "build_date('startdate')",
"End Date" => "build_date('enddate')"
);
foreach($commands as $key => $val) {
echo "<td>$key</td>";
echo "<td>" . eval("return($val);") . "</td>";
}
|
|
|
|
|