2

Hi I have an array created from an XML file using this function.

# LOCATIONS XML HANDLER
#creates array holding values of field selected from XML string $xml
# @param string $xml
# @parm string $field_selection
# return array
#
function locations_xml_handler($xml,$field_selection){

  # Init return array
    $return = array();  
  # Load XML file into SimpleXML object
    $xml_obj = simplexml_load_string($xml);
  # Loop through each location and add data

  foreach($xml_obj->LocationsData[0]->Location as $location){
    $return[] = array("Name" =>$location ->$field_selection,);
   }
  # Return array of locations

    return $return;

}

How can I stop getting duplicate values or remove from array once created?

1
  • Why do you make a two-dimensional array? You can just do $return[] = $location->$field_selection. Commented Jun 4, 2011 at 17:01

2 Answers 2

3

You could simply call array_unique afterwards:

$return = array_unique($return);

But note:

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.

Or, instead of removing duplicates, you could use an additional array for the names and use the uniqueness of PHP’s array keys to avoid duplicates in the first place:

$index = array();
foreach ($xml_obj->LocationsData[0]->Location as $location) {
    if (!array_key_exists($location->$field_selection, $index)) {
        $return[] = array("Name" => $location->$field_selection,);
        $index[$location->$field_selection] = true;
    }
}

But if your names are not string-comparable, you would need a different approach.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Gumbo, Due all index called "Name" this approach does not appear to work. Have tried compare the values but as object and pointers they are different even with same values!
1

http://php.net/manual/en/function.array-unique.php

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);

1 Comment

Thanks Brandon, This does not work as all index are called "Name" and so array_unique returns only first element.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.