当未设置其中一个元素时,表达式返回true。 对象数组

if(isset($cat[$k]->id) && $cat[$k]->id==$nav[$lvl-1]->id) // = false 

But

if($cat[$k]->id==$nav[$lvl-1]->id) // = true

How is it possible?

Your code is probably right, but your statements are returning false.

You need to debug it.

I will write you an example on how to do this, including documentation.

Example:

$test1 = false;
$test2 = null;
$test3 = [];
$test4 = 'asd';
$test5 = 1;

if ($test1)
{
    echo 'Valid';
}
else
{
    echo 'False';
}
// Output: 'False'
// This is because $test1 = false. The if statement will check if $test1 is set/true and not false.

if ( ! $test2)
{
    echo 'NULL';
}
else
{
    echo 'NOT NULL';
}
// Output: 'NULL'
// $test2 is NULL/EMPTY (NULL = not valid)
// For the if( ! ..) part, will say if not.

if (is_array($test3))
{
    echo 'Is array';
}
else
{
    echo 'Is not an array';
}
// Output: 'Is array'
// [] is short for array(); $test3 is an array, so your if statement will continue as valid.

if ( ! empty($test4) || is_integer($test5))
{
    echo 'Valid';
}
else
{
    echo 'Is not valid';
}
// Output: 'Valid'
// Both $test4 and $test5 pass the if statement. Because $test4 is not empty OR $test5 is an integer.

Related to your code:

echo '<pre>';
var_dump($cat[$k]);
echo '</pre>';
die;

if(isset($cat[$k]->id) && $cat[$k]->id==$nav[$lvl-1]->id);

You need to 'debug' your code. You require $cat[$k]->id to be set, if it is not set it will return false.

While debugging you check if the data is parsed correctly or not.

Documentation:


Instead of giving you the right answer right away, I wish to show you how to debug your code and to understand how isset() works. In case you have question, just let me know in a comment.

Good luck!

I find good solution: for the object property better to use function property_exists() - http://php.net/manual/en/function.property-exists.php

Function property_exists() returns TRUE even if the property has the value NULL. Any case, thanks for comments of users, better to know that isset() returns false than argument has the value NULL.