Life of a web developer

November 22, 2010

Tutorial: emptyStr() the end of long unnecessary if statements

Filed under: PHP, Tutorials — Tags: , , — Ole Aass @ 10:33 pm

This is absolutely not a newsflash for anyone that’s been working a bit with PHP. We always come across situations where we need to make sure strings is or isn’t empty, and what’s more boring than having to write the same stuff for each variable? So i thought, why not make it like the isset() that handles an endless number of arguments? So this is what I came up with:

// Initialize the function
function emptyStr() {

	// Collect all the arguments passed to the method
	// and add them to an array
	$args = funct_get_args();

	// Loop through the arguments
	foreach ($args as $key => $value) {

		// If the argument is not an empty string, return false
		if ($value == "") {
			return true;
		}
	}

	// If none of the arguments are empty strings,
	// return true
	return false;
}

Usage:

$var1 = "Hello";
$var2 = "world!";

if (!emptyStr($var1, $var2)) {
	echo $var1.' '.$var2;
} else {
	echo "Failed";
}

The above code will output: Hello world!

Advertisements

2 Comments »

  1. Use full function keep it up 🙂

    Comment by Riyaz — November 23, 2010 @ 10:26 am


RSS feed for comments on this post. TrackBack URI

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

Create a free website or blog at WordPress.com.

%d bloggers like this: