Call me old school, but I don’t think much of the new sitepoint design.
I am trying to get an array of distinct items using the following code…however the function seems to add everything to the array with it’s in the array or not.
Please help
$xml = simplexml_load_file($kyero_xml);
$property_provinces_array = kyero_xml_provinces($xml);
$output = $output.'<p> The kyero feed contains the following distinct provinces</p>';
foreach ($property_provinces_array AS $property_province_name) {
$output = $output.$property_province_name.'<br />';
}
function kyero_xml_provinces($xml) {
$kyero_xml_provinces = array();
foreach ($xml->property as $Property) {
$property_province = $Property->province;
if (!in_array($property_province, $kyero_xml_provinces)) {
array_push($kyero_xml_provinces, $property_province);
}
}
return $kyero_xml_provinces;
}
Is there any chance the array somehow gets a zero in it? I am reading elsewhere that it will always return true if that’s the case, though that might be version dependant.
I don’t see offhand how that would be. Did you do a var_dump() or something right after calling the function to be sure?
And just for fun, here are a couple other ways to get the result you’re after.
Use the value as the key. Then you know for sure only one instance of a value will be in there. This wouldn’t work for values which would be invalid for an array key.
function kyero_xml_provinces($xml) {
$list = array();
foreach ($xml->property as $Property) {
$province = $Property->province;
$list[ $province ] = $province;
}
return $list;
return array_values( $list ); // use this line if you don't want the return value to have those keys
}
Just build the whole list and uniquify it at the end. This might actually be more efficient than the if in your original code, but I don’t know for sure.
function kyero_xml_provinces($xml) {
$list = array();
foreach ($xml->property as $Property) {
$list[] = $Property->province;
}
return array_unique( $list );
}