Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

The code below is being used to retrieve the value of the "store" element from the XML file below and insert the values into an array (the storeArray). I do NOT want duplicate values put into the array (IE I don't want Best Buy inserted twice), so I am using the in_array method to prevent duplication.

This code works fine:

$xmlDoc = simplexml_load_file("products.xml"); $storeArray = array();

foreach($xmlDoc->product as $Product) {
echo "Name: " . $Product->name . ", ";
echo "Price: " . $Product->price . ", ";

if( !in_array( (string)$Product->store, $storeArray )) {
    $storeArray[] = (string)$Product->store;
}}

foreach ($storeArray as $store) {
echo $store . "<br>"; 
}

But when I try to put those array values (from the XML store element) into a link (like below), the values are duplicated (IE Best Buy is displayed twice. Any advice?

if( !in_array( (string)$Product->store, $storeArray )) {
$storeArray[] = "<a href='myLink.htm'>" . (string)$Product->store . "</a>";

foreach ($storeArray as $store) {
echo $store . "<br>";
}

Here is the XML file:

<product type="Electronics">
<name> Desktop</name>
<price>499.99</price>
<store>Best Buy</store>
</product>

<product type="Electronics">
<name>Lap top</name>
<price>599.99</price>
<store>Best Buy</store>
</product>

<product type="Hardware">
<name>Hand Saw</name>
<price>99.99</price>
<store>Lowes</store>
</product>

</products>
share|improve this question

2 Answers 2

up vote 1 down vote accepted

There is an issue with your in_array check. You are checking if the store is in the array, but actually add the link to the array, therefore in_array will always be false.

Bad check:

// you are checking the existance of $Product->store
if (!in_array((string)$Product->store, $storeArray)) {
    // but add something else
    $storeArray[] = "<a href='myLink.htm'>" . (string)$Product->store . "</a>";
}

Instead try using the store as an array key:

$store = (string)$Product->store;

if (!array_key_exists($store, $storeArray)) {
    $storeArray[$store] = "<a href='myLink.htm'>" . $store . "</a>";
}
share|improve this answer
    
Thanks, it works! Should've realized that in_array will always be false with the link! –  Dean Olsen Feb 15 at 19:07

Your approach is fine. It won't add the value to $storeArray twice. I think you have a bug with closing brackets in the second code block you shown. See this phpfiddle - it works:

http://phpfiddle.org/main/code/1ph-6rs

You can also use array_unique() function to print unique values.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.