[PHP]
if(isset($object['prop']) && !is_null($object['prop'])) doSomething();
[/PHP]
OR - the Zend way:
[PHP]
if(isset($object['prop']) && null !== $object['prop']) doSomething();
[/PHP]
Hello,
I'm used to JavaScript where it's quite simple to test if the property of an object is not null:
However in PHP, I can't find any simple way to do it. Each time I want to check if a variable is not null, I first need to check that it is set (to avoid the "undefined index" notice) and then if it is null. i.e.Code:if (object.prop) doSomething();
[PHP]if (isset($object['prop']) && $object['prop']) doSomething();[/PHP]
Is there any way in PHP to do the above in a less verbose way? For example, is there any function that test if a variable is set and non-null?
Thanks,
Laurent
[PHP]
if(isset($object['prop']) && !is_null($object['prop'])) doSomething();
[/PHP]
OR - the Zend way:
[PHP]
if(isset($object['prop']) && null !== $object['prop']) doSomething();
[/PHP]
Actually, I was looking for a less verbose way to do thatAs I mentioned above, in javascript, it's as simple as "if (object.prop)" while in PHP I have to write a very lengthy statement, which makes the code very heavy for not real benefit.
So is it possible to do something like "if ($object['prop'])" in PHP? or maybe is there a function such as "isNotSetOrNull()"?
if ($object['prop']) will only tell you if $object['prop'] === true or false. if the index 'prop' is not set then that statement will throw an 'undefined index' exception. there is no function "isNotSetOrNull()" that I know of, although I guess you could write one yourself if it's really that much of a concern...
Quick correction, if ($object['prop']) will tell you if $object['prop'] == true. The expression ($object['prop']) will be evaluated as a boolean.If you want to bypass the E_NOTICE for an undefined variable or index, you can use !empty() to see if the variable is 1) set, and 2) evaluates to true -- empty would be false, but we negate that with the !Originally Posted by PHP.net
99% of the time we know (or SHOULD know, validate input!) what types we are dealing with, so IMO it's fine to use lazy typing like this. The code you have now checks to see that the value is declared and is null. That's a rare condition to have to check for, honestly.
Last edited by SirAdrian; 04-16-2009 at 04:54 PM.
yea that makes sense. I thought empty() only worked on arrays? But it turns out that you are absolutely correct:
thank you for pointing that out. the only problem would be - what if you are running empty() on a variable that is set to 0 or '0' and it is legitimately supposed to be set to 0? according to the docs it would consider that to be empty. this has caused me problems before when a null value is invalid input but 0 is not, which is why i had originally began using isset() and null ===Originally Posted by http://us3.php.net/empty
Last edited by Rhino; 04-16-2009 at 05:10 PM.