isset or not isset

If you work with PHP for a long time, you probably get used to the code like this:

<?php 
if (isset($_POST['username']) && isset($_POST['password']) {
	$this->login($_POST['username'], $_POST['password'])
}

the magic of isset is that it is short and explicitly tells what it does — checks if the $var has some “meaningful” value.

By using it zillion times, you might get used to it as a quick check if the key exists in array as in the above example. But here is the caveat. Suppose you have a hash-array containing user profile fields like “Name”, “Website”, and blablabla and at the end – “About me”. So you would like to print it like this:

Name: Ford Prefect
Website: http://h2g2.com
...
-------
Something about me: Always have a towel

What you could come up for this is something like that:

<?php
if (isset($profile['About me'])) {
	$aboutMe = $profile['About me'];
	unset($profile['About me']);
}
foreach ($profile as $field => $value) {
	echo $field . ': ' . $value . "\n";
}
echo "-------\n";
if (isset($aboutMe)) {
	echo "Something about me: " . $aboutMe;
}

Will it work?

Well, not exactly. Think of what happens if “About me” is NULL.

This is what happens:

Name: Ford Prefect
Website: http://h2g2.com
About me: 
-------

So the “About me” suddenly jumps from under the line over it. Why did it happen? I thought we explicitly removed the “About me” from array.

The problem is in the very first line. In reality if (isset($profile['About me'])) returns false not only if the key does not exist in array, but also in the case where it exists but its value is NULL. So the correct way would be to use array_key_exists function and then: problem is solved.

Now this example was pretty naive but I recently found same error in Array2XML convertor and there it produced exceptions because of not deleted tags. So be careful.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.