...

View Full Version : how to compare 2 arrays ?



graziano
11-21-2006, 08:04 AM
Hello

I am having problems comparing 2 arrays .

I have $domains[] which contains 3 values

123.com
456.com
789.com

and $data[] which contains 3 values arriving from a data file

566.com
789.com
555.com


I wish to compare the array $domains[] with array $data[] (each value of array $domains[] with
each value of $data[] ) . I wish to echo "OK" if two arrays are the same (==),
I wish to echo "FAIL" if the arrays are not the same.
So the result of the script should be

$domains[] compare result
123.com FAIL
456.com FAIL
789.com OK



I am trying in this way



...
...
$data_file = '/data.txt';
if (!empty($HTTP_POST_VARS['is_sent'])) process_form();
$data = file($data_file);
$count_data = count($data);

$countx=3;
for ($x = 0; $x < $countx; $x++)
{

echo"$domains[$x]";
for ($xc = 0; $xc <= $count_data-1 ; $xc++)
{
$data[$xr] = trim($data[$xr]);

if ( $domains[$x] == $data[$xc] ) {
echo "OK<br>";
# stop $xc for cycle because condition verified
$xr=$count_data;
}
else
{
echo "FAIL;
}
}
}




but it doesn't work ..

Is there a better way to do the work ?

Thank you!

SeeIT Solutions
11-21-2006, 08:12 AM
Try this...


...
...
$data_file = '/data.txt';
if (!empty($HTTP_POST_VARS['is_sent'])) process_form();
$data = file($data_file);

foreach ($domains as $domain) {
if (in_array($domain,$data)) {
echo $domain." - OK<br>";
} else {
echo $domain." - FAIL<br>";
}
}

graziano
11-21-2006, 09:30 AM
Thank you

Your code is right , unluckly it fails because
I noticed that the array which arrives from $data contains some space in their values

argh...

SeeIT Solutions
11-21-2006, 09:51 AM
if the spaces are at the beginning and end of each element you could do this...


...
$data = file($data_file);

for ($i = 0; $i< count($data);$i++) {
$data[$i] = trim($data[$i]);
}

foreach ($domains as $domain) {
...

graziano
11-21-2006, 02:31 PM
My code and your was not working because I had some space on the array $data . This was the solution

########################################
$data = array_map('trim', $data );
########################################

I found it on php.net (on a note) . I needed 4 hours to find this solution , and I have still to understand why "$data[$x]=str_replace(' ','',$data[$x]); " was not accepted (it didn't remove spaces from array) .

THANK YOU however



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum