tags:

views:

93

answers:

3

The code is short,but complete:

function process($obj)
{
    if(empty($obj))return 1;
    return 2;
}


echo process($arr['nosuchkey']);

As we all know, calling empty($arr['nosuchkey']) will never report warnings.

But process($arr['nosuchkey']) will report a notice.

Is there a workaround without disabling warnings; say, by syntax?

+4  A: 

You can use the error control operator @ but that will suppress a lot more than just notices.

echo @process($arr['nosuchkey']);

You would be better off checking before the function call:

if (array_key_exists('nosuchkey', $arr))
    echo process($arr['nosuchkey']);

Or passing the key separately

echo process($arr, 'nosuchkey');

Be sure you know the difference between empty(), isset() and array_key_exists() - they catch a lot of people out.

Greg
Checking before the function will render function absolutely useless
Cem Kalyoncu
Yes, please avoid the @ operator.
smack0007
I'd assume this is a somewhat cut-down example...
Greg
+2  A: 

Try this one

 function process(&$obj)

Im not sure if it will work

Cem Kalyoncu
It works. That’s what I was about to write too.
Gumbo
I remembered not working,but not sure.
Shore
A: 

Maybe

function process($obj, $index = null) {
    if(is_array($obj))
    {
         if(!array_key_exists($index, $obj))
             return 1;
         else
             return 2;
    }

    if(empty($obj)) 
        return 1;

    return 2;

}

Please don't hide warnings with @ whenever possible.

macbirdie