I would like to insert variables in an array. I am using in_array() function to check if a value has already been inserted and array_push to append elements to the array.
Working example
<?php
$var1="cat";
$var2="dog";
$var3="gepp";
$var4="frigor";
$var5="dog";
$var6='cat';
$array1=array($var1,$var2,$var3,$var4,$var5,$var6);
$ya=array();
for($i=0;$i<=count($ya);$i++)
{
if (in_array($array1[$i],$ya,true))
{
echo $i . " : Yess<br>";
}
else
{
array_push($ya, $array1[$i]);
echo $i . " : Noo<br>";
}
}
echo "<br>\n";
print_r($array1);
echo "<br>\n";
print_r($ya);
?>
The output is:
0 : Noo 1 : Noo 2 : Noo 3 : Noo 4 : Yess
Array ( [0] => cat [1] => dog [2] => gepp [3] => frigor [4] => dog [5] => cat )
Array ( [0] => cat [1] => dog [2] => gepp [3] => frigor )
Not working example
In the following code values are saved from the label tag of an xml.
$array = array();
foreach($mypix->result as $pixinfo):
echo " Result<br>\n ";
foreach($pixinfo->row as $row):
$label=$row->label;
if (in_array($label,$array,true))
{
echo "Yess<br>";
}
else
{
array_push($array, $label);
echo "No<br>";
}
echo "[NEXT]<br>\n";
endforeach;
endforeach;
The xml's structure is as follows:
<result date="2014-05-05">
<row>
<label>1.1</label>
<nb_visits>4</nb_visits>
</row>
</result>
<result date="2014-05-06"/>
<result date="2014-05-08">
<row>
<label>Custom Variable value not defined</label>
<nb_visits>115</nb_visits>
<nb_actions>261</nb_actions>
</row>
<row>
<label>Commedia</label>
<nb_visits>26</nb_visits>
<nb_actions>39</nb_actions>
</row>
[...]
</result>
The problem is that values are inserted even if they are already present in the array.
Do you guys have any advice? What's wrong with the in_array command?
Edit
Here is the output of var_dump($array);
array(441){
[0]=> object(SimpleXMLElement)#9 (1) { [0]=> string(3) "1.1" }
[1]=> object(SimpleXMLElement)#8 (1) { [0]=> string(3) "1.2" }
[2]=> object(SimpleXMLElement)#10 (1) { [0]=> string(3) "1.1" }
[3]=> object(SimpleXMLElement)#11 (1) { [0]=> string(3) "1.1" }
[4]=> object(SimpleXMLElement)#12 (1) { [0]=> string(33) "Custom Variable value not defined" }
var_dump($array)