0

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>

2 Answers 2

1

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>";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it works! Should've realized that in_array will always be false with the link!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.