Simple PHP Function For Inline Comparisons

This will probably seem trivial and obvious to most PHP users out there but some of you might find this simple function useful. There are a lot of times when you’ll want to do a quick comparison and then, for example, give an HTML element a specific class based on what you found. The following is a short and sweet function I include in all of my projects to make this easy to do:

<?php
	function check_equal($val1, $val2, $response)
	{
		if ($val1 == $val2)
		{
			return $response;
		}
	}
?>

Here’s an example of this function in action:

<?php
	echo '<div'.check_equal($user, 1, ' class="author"').'>';
?>

In the example above, whenever the value of $user is equal to 1 then the div will be written out with the class of “author” attached to it. Now I can make some changes to my CSS to style that div differently based on the value of the PHP variable $user.

January 1st, 2008 | PHP, Programming | 0 Comments

No Comments

Leave a comment...