note 21121 added to function.eval
| From: | spam at krubner dot com | Date: | Tue, 30 Apr 2002 01:10:07 +0000 |
| Subject: | note 21121 added to function.eval | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-30001@lists.php.net to get a copy of this message | ||
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");
--
http://www.php.net/manual/en/function.eval.php
http://master.php.net/manage/user-notes.php?action=edit+21121
http://master.php.net/manage/user-notes.php?action=delete+21121
http://master.php.net/manage/user-notes.php?action=reject+21121