ranwilli
ranwilli

Reputation: 56

in_array not functioning as I understand it should do

I have this code:

<ul style="list-style-type:none;">
<?php foreach ($rawmenuitems as $rawmenuitem) 
    { 
    if (in_array($rawmenuitem->note, $completedmenuitems))
    { ?>
        <li>
        <span style="color:#666666; "><?php echo ($rawmenuitem->title); ?></span>
        </li>
<?php   }
    else
    { ?>
        <li>
        <?php echo ('<a href =' . $rawmenuitem->link . '&amp;Itemid=' . $rawmenuitem->id . '">' . $rawmenuitem->title . '</a>'); ?>
        </li>
<?php   }
}?>
</ul>

the arrays are:

$rawmenuitems ( 
[0] => stdClass Object ( [link] => index.php?option=com_breezingforms&view=form [id] => 1378 [title] => 334 Basic Information [note] => 5 ) 
[1] => stdClass Object ( [link] => index.php?option=com_breezingforms&view=form [id] => 1381 [title] => 334 Drug Testing [note] => 17 ) 
[2] => stdClass Object ( [link] => index.php?option=com_breezingforms&view=form [id] => 1380 [title] => 334 Emergency Treatment [note] => 15 ) 
[3] => stdClass Object ( [link] => index.php?option=com_breezingforms&view=form [id] => 1379 [title] => 334 Extracurricular [note] => 7 ) 
[4] => stdClass Object ( [link] => index.php?option=com_breezingforms&view=form [id] => 1377 [title] => 334 Florida Concussion [note] => 12 ) 
[5] => stdClass Object ( [link] => index.php?option=com_breezingforms&view=form [id] => 1376 [title] => 334 Florida Consent [note] => 14 )
) 

and

$completedmenuitems ( 
[0] => stdClass Object ( [id] => 1377 [note] => 12 ) 
[1] => stdClass Object ( [id] => 1376 [note] => 14 ) 
)

But the output of the code is just the six links, without regard to the result of the conditional. Any ideas?

Upvotes: 0

Views: 135

Answers (2)

Andy
Andy

Reputation: 1043

Those are arrays of objects - so in array $completedmenuitems there is no object "5". There is object that has property note = 5.

You have to extract note from objects from array to other array.

$completedmenuitems_notes = array_map(
    create_function(
        '$object', 
        'return $object->note;'
    ), 
    $completedmenuitems
);

Upvotes: 3

ComFreek
ComFreek

Reputation: 29434

$rawmenuitem->note is an integer whereas $completedmenuitems is an array of objects containing an attribute called note. Therefore, in_array() compares integers with objects.

There are multiple solutions to this problem. One would be to roll his own function:

function isCompletedItem($completedItems, $note) {
  foreach ($completedItems => $items) {
    if ($items->note == $note) {
      return true;
    }
  }
  return false;
}

if (in_array($completedmenuitems, $rawmenuitem->note))

Upvotes: 0

Related Questions