noreason noreason - 1 year ago 130
PHP Question

PHP Array Comparison using If

I am having a hard time trying to understand why I can't compare the values of two arrays in PHP. If I echo both of these during the loop using "echo $description->ItemDesriptionName;" and "echo $item->ItemName;" the values seem to show as the same, but when I try to compare them using if, nothing works. What am I missing?


$xml=simplexml_load_file("test.xml") or die("Error: Cannot create object");
$categories = $xml->Menu->Categories;
$items = $xml->Menu->Categories->Items->ItemObject;
$itemdescription = $xml->Menu->Options->Description->DescriptionObject;

foreach($items as $item) {

echo $item->ItemName . ' - ' . $item->Price . '</br>';

foreach ($itemdescription as $description) {

if ($description->ItemDescriptionName == $item->ItemName) {
echo 'We have a match!';
//where I would echo $description->ItemDescription;


Here is the XML file

<?xml version="1.0" encoding="utf-8"?>
<Name>Category 1</Name>
<ItemName>Item 1</ItemName>
<ItemName>Item 2</ItemName>
<ItemDescriptionName>Item 1</ItemDescriptionName>
<ItemDescription>A Great item</ItemDescription>
<ItemDescriptionName>Item 2</ItemDescriptionName>
<ItemDescription>A Great item as well</ItemDescription>

Answer Source

compare as string and you have typo in ItemDescriptioName (ItemDescriptionName)

if ( (string)$description->ItemDescriptionName == (string)$item->ItemName) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download