in_array not working

I pull out town names $poblacion from my XML.

If the town name isn’t in the array I wish to add it (array_push)…however it always isn’t in the array. Am I doing something wrong ?

$solvia_xml_distinct_poblacions= array();
foreach($xml->products as $products) {
	$poblacion = $products->poblacion;
	if(in_array($poblacion, $solvia_xml_distinct_poblacions)) {
		$output = $output.'IN '.$poblacion.'<br />';
	}
	else {
		$output = $output.'OUT '.$poblacion.'<br />';
		array_push($solvia_xml_distinct_poblacions, $poblacion);
	}
}

I got it to work using (trim)…but I need to sort the town names alphabetically…and that doesn’t work.

function solvia_xml_distinct_poblacions($xml) {
	$solvia_xml_distinct_poblacions= array();
	foreach($xml->products as $products) {
		$poblacion = trim($products->poblacion);
			if(!in_array($poblacion, $solvia_xml_distinct_poblacions)) {
				
			}
		}
	$solvia_xml_distinct_poblacions = 	sort($solvia_xml_distinct_poblacions);
	return $solvia_xml_distinct_poblacions;
}

Try asort() instead

BTW, can you please edit your post by

enclosing the code block in 3 backticks
```
on their own lines.

1 Like

Hi Mittineague
What do you mean by “3 backticks” ?

indent preformatted text by 4 spaces

function solvia_xml_distinct_poblacions($xml) {
	$solvia_xml_distinct_poblacions= array();
	foreach($xml->products as $products) {
		$poblacion = trim($products->poblacion);
			if(!in_array($poblacion, $solvia_xml_distinct_poblacions)) {
				array_push($solvia_xml_distinct_poblacions, $poblacion);
			}
		}
	//$solvia_xml_distinct_poblacions = 	asort($solvia_xml_distinct_poblacions);
	return $solvia_xml_distinct_poblacions;
}

asort isn’t working for some reason

Not because I have commented out

//$solvia_xml_distinct_poblacions = asort($solvia_xml_distinct_poblacions);

What does
var_dump($solvia_xml_distinct_poblacions);
give you, an empty array or an unsorted array?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.