Compare array in loop
- by user3626084
I have 2 arrays with different sizes, in some cases one array can have more elements than the other array. However, I always need to compare the arrays using the same id. I need to get the other value with the same id in the other array
I have tried this, but the problem happens when I compare the two arrays in a loop when the other array has more elements than one, because duplicate the loop and data , and it does not work.
Here is what I've tried:
<?php
/// Actual Data Arrays ///
$data_1=array("a1-fruits","b1-apple","c1-banana","d1-chocolate","e1-pear");
$data_2=array("b1-cars","e1-eggs");
///
for ($i=0;$i<count($data_1);$i++)
{
/// Explode ID $data_1 ///
$exp_id=explode("-",$data_1[$i]);
///
for ($h=0;$h<count($data_2);$h++)
{
/// Explode ID $data_2 ///
$exp_id2=explode("-",$data_2[$h]);
///
if ($exp_id[0]=="".$exp_id2[0]."")
{
print "".$data_2[$h]."";
print "<br>";
}
else
{
print "".$data_1[$i]."";
print "<br>";
}
///
}
///
}
?>
I want the following values :
"a1-fruits"
"b1-cars"
"c1-banana"
"d1-chocolate"
"e1-eggs"
Yet, I get this (which isn't what I want):
a1-fruits
a1-fruits
b1-cars
b1-apple
c1-banana
c1-banana
d1-chocolate
d1-chocolate
e1-pear
e1-eggs
I tried everything I know and try to understand how I can do this because I don't understand how to compare these two arrays. The other problem is when one size has more elements than the other, the comparison always gives an error.
I FIND THE SOLUTION TO THIS AND WORKING IN ALL :
<?php
/// Actual Data Arrays ///
$data_1=array("a1-fruits","b1-apple","c1-banana","d1-chocolate","e1-pear");
$data_2=array("b1-cars","e1-eggs","d1-chocolate2");
///
for ($i=0;$i<count($data_1);$i++)
{
$show="bad";
/// Explode ID $data_1 ///
$exp_id=explode("-",$data_1[$i]);
///
for ($h=0;$h<count($data_2);$h++)
{
/// Explode ID $data_2 ///
$exp_id2=explode("-",$data_2[$h]);
///
if ($exp_id2[0]=="".$exp_id[0]."")
{
$show="ok";
print "".$data_2[$h]."<br>";
}
///
}
if ($show=="bad")
{
print "".$data_1[$i]."";
print "<br>";
}
///
}
?>