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);
About these ads

September 16, 2009 - Posted by | Code, PHP | , , , , , ,

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: