Very very simple function

From: Date: Thu, 20 Jun 2002 23:09:59 +0000
Subject: Very very simple function
Groups: php.smarty.general 
Request: Send a blank email to php-smarty-general+get-4961@lists.php.net to get a copy of this message
I wrote the simplest possible plugin function for Smarty. Basically it is a wrapper for mt_rand. I use this function a lot and randomising functionality is always nice to have, whether to display a random image or whatever. I'd like to suggest that it goes into the distribution, for no reason other than that random selection means variety and variety is the spice of life. Two things I'm not sure about. I call mt_srand(time()) in the file but not in the function. If I call it in the function you just get the same random number produced because the output of time() doesn't change. I could use microtime, but if there's nothing wrong with calling mt_srand in the file then it makes sense to me to do it that way. The other thing is that if random is called with non-integer numbers, they are rounded (by using ceil and floor on the params). If the params are not numeric there are error messages that say 'please use a number'. This is technically correct, but it would be more useful if people chose integers. But that wouldn't convey the fact that they can just choose numbers, so the rounding is a kind of null feature. Egg, chicken, egg, chicken... face, desk, slam! Anyway, I hope you like my function, even if you just look at and say "I could have written that in one minute using three lines of code and a question mark." Ben ----------------- function.random.php <? /* * Smarty plugin * -------------------------------------------------------------
	 * File:     function.random.php
	 * Type:     function
	 * Name:     random
* Author: Ben Godfrey <ben@hypothetical.co.uk> * Purpose: outputs a random number in the range specified by min and max attribs or 0 and mt_randmax
	 * Usage:    {random min=0 max=10}, {random min=-10}, {random max=20} or just {random}
* ------------------------------------------------------------- */ function smarty_function_random($params, &$smarty) { extract($params); if (empty($min)) $min = 0; if (empty($max)) $max = mt_getrandmax(); // complain about erroneous args if (!is_numeric($min)) { $smarty->trigger_error("random: parameter 'min' must be a number"); return; } if (!is_numeric($max)) { $smarty->trigger_error("random: parameter 'max' must be a number"); return; } print(mt_rand(floor($min), ceil($max))); } // initialise random number sequence mt_srand(time()); ?> ------------- end

« previous php.smarty.general (#4961) next »