Forum Moderators: coopster

Message Too Old, No Replies

Compare contents of two arrays and display what DOESN'T match

What's the easiest, most efficient way?

         

neophyte

11:33 pm on Oct 17, 2006 (gmt 0)

10+ Year Member



Hello All -

I've got two arrays that I need to compare. One is $roomNums and the other is $roomNumsBooked. The point is to compare $roomNumsBooked against $roomNums (both arrays) and then display what DOESN'T match so I can get the rooms currently available.

I've written a script that works, but it seems every-so-clumsy. I was wondering if I could somehow use preg_match to do this but my prevous experiments have failed. Here's what I've done that works:

*******************************************

$roomNums = array('A','B','H','J','K','L','M','P','T');
$roomNumsBooked = array('A','B','L','T');

for ($i = 0; $i < count($roomNumsBooked); $i++)
{
for ($j = 0; $j < count($roomNums); $j++)
{
if ($roomNums[$j] == $roomNumsBooked[$i])
{
$roomNums[$j] = '0';
}
}
}

print_r ($roomNums);
echo '<br>';

echo 'Available Rooms: ';

for ($i = 0; $i < count($roomNums); $i++)
{
if ($roomNums[$i]!= '0')
{
echo $roomNums[$i] , ', ';
}
}

*******************************************

The echoed result is H, J, K, M, P which is correct, but is there a better, more efficient and/or elegant way to do this?

Neophyte

Psychopsia

12:31 am on Oct 18, 2006 (gmt 0)

10+ Year Member



Hi neophyte:

You can use array_diff [us2.php.net], to get the same result.

I tested this code:

$roomNums = array('A','B','H','J','K','L','M','P','T');
$roomNumsBooked = array('A','B','L','T');

$available = array_diff($roomNums, $roomNumsBooked);

print_r($available);

echo '<br /><br />' . implode(', ', $available);

[edited by: Psychopsia at 12:33 am (utc) on Oct. 18, 2006]

neophyte

1:11 am on Oct 18, 2006 (gmt 0)

10+ Year Member



Psychopsia -

That's the absolute perfect solution to my issue.

Thanks so much for the guidance!

Neophyte

neophyte

2:03 am on Oct 18, 2006 (gmt 0)

10+ Year Member



Follow-on question:

I'm noticing that $available keeps the same number of indeces (sp?) as the longest comparison array, albiet indeces which have been "matched" are "empty".

is there another built-in fuction that would re-read $available into a new array so index[0] (and others) are populated with the found differences... or would re-order $available so that empty indexs would be thrown out and difference values wold start at index[0]?

Neophyte