php

wrand(); // a php weighted randomization function

dan from todaywasawesome just asked me to help him with a weighted randomization function in php. i thought my solution was cool, if a bit simplistic. like everything else i want to keep around, i'm posting it in my blag. enjoy!

/* this function expects either an array
 * ordered by weight, or with exact weights
 * as it's array indices.
 * it will return a randomly selected value.
 */
function wrand($data) {
	$totalw = $curw = 0;
	
	foreach ($data as $i => $val) {
		$totalw += $i;
	}
	
	$rand = rand(0,$totalw);
	
	foreach ($data as $i => $val) {
		if ($curw >= $rand) return $val;
		$curw += $i;
	}
	
	return array_pop($data);
}

snippet of the day: trim a string (the smart way) with php

i reworked the feed reading signature images i made a while back and added something to trim the strings to a decent length without breaking words. so here you go. a one-liner that'll trim a string to a decent length, and break it on whitespace:

if (strlen($blog_title) > 35) $blog_title =
array_shift(explode("|||", wordwrap($blog_title,
35, "|||"))) . "...";