Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid isset() and empty()

I have several older applications that throw a lot of "xyz is undefined" and "undefined offset" messages when running on the E_NOTICE error level, because the existence of variables is not explicitly checked using isset() and consorts.

I am considering working through them to make them E_NOTICE compatible, as notices about missing variables or offsets can be lifesavers, there may be some minor performance improvements to be gained, and it's overall the cleaner way.

However, I don't like what inflicting hundreds of isset() empty() and array_key_exists() s does to my code. It gets bloated, becomes less readable, without gaining anything in terms of value or meaning.

How can I structure my code without an excess of variable checks, while also being E_NOTICE compatible?

like image 906
Pekka Avatar asked Dec 25 '09 04:12

Pekka


People also ask

Can I use empty instead of isset?

isset() returns false only when the variable exists and is not set to null , so if you use it you'll get true for empty strings ( '' ). empty() considers both null and '' empty, but it also considers '0' empty, which is a problem in some use cases. If you want to treat '0' as empty, then use empty() .

Does empty check for isset?

The isset() and ! empty() functions are similar and both will return the same results. But the only difference is ! empty() function will not generate any warning or e-notice when the variable does not exists.

What can I use instead of isset in PHP?

The equivalent of isset($var) for a function return value is func() === null . isset basically does a !== null comparison, without throwing an error if the tested variable does not exist.

What is the use of isset () and unset ()?

PHP isset() Function This function returns true if the variable exists and is not NULL, otherwise it returns false. Note: If multiple variables are supplied, then this function will return true only if all of the variables are set. Tip: A variable can be unset with the unset() function.


1 Answers

For those interested, I have expanded this topic into a small article, which provides the below information in a somewhat better structured form: The Definitive Guide To PHP's isset And empty


IMHO you should think about not just making the app "E_NOTICE compatible", but restructuring the whole thing. Having hundreds of points in your code that regularly try to use non-existent variables sounds like a rather badly structured program. Trying to access non-existent variables should never ever happen, other languages balk at this at compile time. The fact that PHP allows you to do it doesn't mean you should.

These warnings are there to help you, not to annoy you. If you get a warning "You're trying to work with something that doesn't exist!", your reaction should be "Oops, my bad, let me fix that ASAP." How else are you going to tell the difference between "variables that work just fine undefined" and honestly wrong code that may lead to serious errors? This is also the reason why you always, always, develop with error reporting turned to 11 and keep plugging away at your code until not a single NOTICE is issued. Turning error reporting off is for production environments only, to avoid information leakage and provide a better user experience even in the face of buggy code.


To elaborate:

You will always need isset or empty somewhere in your code, the only way to reduce their occurrence is to initialize your variables properly. Depending on the situation there are different ways to do that:

Function arguments:

function foo ($bar, $baz = null) { ... } 

There's no need to check whether $bar or $baz are set inside the function because you just set them, all you need to worry about is if their value evaluates to true or false (or whatever else).

Regular variables anywhere:

$foo = null; $bar = $baz = 'default value'; 

Initialize your variables at the top of a block of code in which you're going to use them. This solves the !isset problem, ensures that your variables always have a known default value, gives the reader an idea of what the following code will work on and thereby also serves as a sort of self-documentation.

Arrays:

$defaults = array('foo' => false, 'bar' => true, 'baz' => 'default value'); $values = array_merge($defaults, $incoming_array); 

The same thing as above, you're initializing the array with default values and overwrite them with actual values.

In the remaining cases, let's say a template where you're outputting values that may or may not be set by a controller, you'll just have to check:

<table>     <?php if (!empty($foo) && is_array($foo)) : ?>         <?php foreach ($foo as $bar) : ?>             <tr>...</tr>         <?php endforeach; ?>     <?php else : ?>         <tr><td>No Foo!</td></tr>     <?php endif; ?> </table> 

If you find yourself regularly using array_key_exists, you should evaluate what you're using it for. The only time it makes a difference is here:

$array = array('key' => null); isset($array['key']); // false array_key_exists('key', $array); // true 

As stated above though, if you're properly initializing your variables, you don't need to check if the key exists or not, because you know it does. If you're getting the array from an external source, the value will most likely not be null but '', 0, '0', false or something like it, i.e. a value you can evaluate with isset or empty, depending on your intent. If you regularly set an array key to null and want it to mean anything but false, i.e. if in the above example the differing results of isset and array_key_exists make a difference to your program logic, you should ask yourself why. The mere existence of a variable shouldn't be important, only its value should be of consequence. If the key is a true/false flag, then use true or false, not null. The only exception to this would be 3rd party libraries that want null to mean something, but since null is so hard to detect in PHP I have yet to find any library that does this.

like image 86
deceze Avatar answered Sep 28 '22 01:09

deceze