Hate My Blog

Allowing Mixed Function Arguments with PHP

Some times you need function to work on a string, or maybe and array of strings. While just coding it to expect a string, with a little more code, you can use a little ingenuity to have it work doubly so.

I whipped up this little example:

function do_it($what){
	if(is_array($what)){
		foreach($what as $x)
			do_it($x);
		return;
	}
	echo "I am $what\n";
}
do_it("working");
do_it(array("running","sleeping","eating"));

gives us

I am working
I am running
I am sleeping
I am eating

a somewhat more complex example below. This will multiply $a & $b into another array of $z.

function ab_mult($a,$b,&$z){
	if(is_array($a)){			//is var $a an array?
		foreach($a as $x)		//loop thru it
			ab_mult($x,$b,$z);	//call its self with the 1 $a var, and leaving $b untouched.
		return;
	}
	if(is_array($b)){			//this is the catch for $b
		foreach($b as $y)
			ab_mult($a,$y,$z);
		return;			//in our case we must return after the loop!!!
	}
	//this is where your actualy function should begin
	$z[] = $a.$b;
}

$a=range('a', 'z');
$b=range(0, 9);

$z=array();
ab_mult($a,$b,$z);

var_dump($z);

September 16, 2009 Posted by | Code, PHP | , , , , , , | Leave a comment

Fuzzy status of who’s online at reddit

This is some quick and dirty little code to test without much precision if any particular user is online over at Reddit.

$url=’http://www.reddit.com/user/HattoriHanzo.json’;

//get the url | json decode it to an array
$j=json_decode(file_get_contents($url),1);
//this just grabs the first element and then its timestamp
$t=$j[data][children][0][data][created_utc];

//this is a delay of 15 min. use std. timestamp math
if((time()-$t) < (60 * 15)){ //and they are online ;) } //or offline ;( [/sourcecode]

September 10, 2009 Posted by | Code, PHP | , , , , | 1 Comment