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){
		foreach($what as $x)
	echo "I am $what\n";

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.
	if(is_array($b)){			//this is the catch for $b
		foreach($b as $y)
		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);



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

%d bloggers like this: