Am I using in_array correctly?

Hi Sitepointers,

I am trying to get unique items into an array from an XML file.

However my code is puching every item into the array, Where am I going wrong?

Many thanks

<?php

$xml = simplexml_load_file('mercers.xml');

$property_distinct_beds = array();
foreach($xml->property as $property) {
	$property_bedrooms = $property->beds;
	if (!in_array($property_bedrooms, $property_distinct_beds, TRUE)) {
		array_push($property_distinct_beds, $property_bedrooms);
	}
}


foreach ($property_distinct_beds as $distinct_beds) {
	echo $distinct_beds.'<br />';
}

?>

The files are located:
http://www.spanishproperty.es/mobile/xml_test.php
http://www.spanishproperty.es/mobile/mercers.xml

Probably a type issue. Try casting your property_bedrooms to int type.

Surely since it’s the same variable type going into the array and we are comparing the same type using in_array, it should work.

In any case I tried the following and it still doesn’t work.

$xml = simplexml_load_file('mercers.xml');

$property_distinct_beds = array();
foreach($xml->property as $property) {
	$property_bedrooms = (int) trim($property->beds);
	if (in_array($property_bedrooms, $property_distinct_beds)) {
		array_push($property_distinct_beds, $property_bedrooms);
	}
}


foreach ($property_distinct_beds as $distinct_beds) {
	echo $distinct_beds.'<br />';
}

Why did you remove negation(!) on if sentence? If you add it, it works properly.

No it doesn’t

<?php

$xml = simplexml_load_file('mercers.xml');
$property_distinct_beds = array();
foreach($xml->property as $property) {
	$property_bedrooms = $property->beds;
	if (!in_array($property_bedrooms, $property_distinct_beds)) {
		array_push($property_distinct_beds, $property_bedrooms);
	}
}


foreach ($property_distinct_beds as $distinct_beds) {
	echo $distinct_beds.'<br />';
}

?>

I used this:


 <?php

$xml = simplexml_load_file('mercers.xml');

$property_distinct_beds = array();
foreach($xml->property as $property) {
    $property_bedrooms = (int) trim($property->beds);
    if (!in_array($property_bedrooms, $property_distinct_beds)) {
        array_push($property_distinct_beds, $property_bedrooms);
    }
}


foreach ($property_distinct_beds as $distinct_beds) {
    echo $distinct_beds.'<br />';
}

?>

This produces the following output:
2
3
4
5
1
6
7
0

Is this not what you intended?

Thanks for your help.

Yes that works.

That is what was intended.

My mistake.