note 21121 deleted from function.eval by didou
| From: | didou@php.net | Date: | Thu, 11 Dec 2003 12:11:03 +0000 |
| Subject: | note 21121 deleted from function.eval by didou | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-61795@lists.php.net to get a copy of this message | ||
Note Submitter: spam@krubner.com
----
To everyone who didn't know this, and as I just learned the hard way, eval() returns nothing,
so you can't do this:
$str = "mysql_query('SELECT * FROM myDb')";
$databaseResult = eval ("\$str = \"$str\";");
A note above suggests using the return() function, and though I read that comment beforehand, I did
not understand it. Most of us who've worked with PHP for awhile will fall into the assumption
that a PHP function will return its result. Such an assumption only brings grief when you have to
deal with eval().
However, I also learned that the PHP interpreter will sometimes read a string as if it was code, for
reasons I don't entirely understand. I wanted a function that would walk through a 2
dimensional array and apply a PHP function to every element. I came up with the following function.
Since I was passing the name of the function as a string, I at first assumed that I needed eval() to
make PHP interpret the string as a function. But in the end, I found this was not so. The following
function works, despite being passed a function name in a string.
function processArray($dbArray, $function){
$processedArray = array();
for ($row = 0; $row < count($dbArray); $row++) {
for ($element = 0; isset($dbArray[$row][$element]); $element++) {
$processedArray[$row][$element] = $function($dbArray[$row][$element]);
}
}
return $processedArray;
}
$db = array('dog', 'cat', 'snake');
$db2 = array('nasty', 'rotten', 'no good');
$db3 = array($db, $db2);
$db3 = processArray($db3, "strtoupper");