Reputation: 21
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?
Upvotes: 2
Views: 711
Reputation: 655239
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.
Upvotes: 3
Reputation: 862
http://php.net/manual/en/function.array-unique.php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
Upvotes: 1