Reply to Re: If you're good with arrays and lists, this one's for you

Your name:

Reply:


Posted by Rik on 12/15/06 11:23

Toby Inkster wrote:
> laredotornado@zipmail.com wrote:
>
>> $list1 = "2,26,345";
>> $list2 = "3,4,26,35,525";
>>
>> I am wondering if there is a short way of determining if all the
>> numbers in $list1 occur in $list2.
>
> Fast or easy?
>
> Easy:
>
> $arr1 = explode(',', $list1);
> $arr2 = explode(',', $list2);
> $allin = TRUE;
> foreach ($arr1 as $n)
> {
> if (!in_array($n, $arr2))
> {
> $allin = FALSE;
> break 1;
> }
> }
> // $allin is now TRUE iff every number in $list1 is in $list2.
>
> Fast:
>
> /***************************************************************
> * We exploit the fact that $list1 and $list2 are sorted lists.
> * This will speed things up, but will only be noticeable when
> * dealing with lists of many hundreds of numbers.
> ***************************************************************/
> $arr1 = explode(',', $list1);
> $arr2 = explode(',', $list2);
> $allin = TRUE;
> while (isset($arr1[0]))
> {
> $n = (int)array_shift($arr1);
> while ((int)$arr2[0] < $n)
> array_shift($arr2);
> if ((int)$arr2[0]>$n)
> {
> $allin = FALSE;
> break 1;
> }
> }

Well, and now ths short code version (not more efficient (only if you
needed the difference)):

$difference = array_diff(explode(',',$list1),explode(',',$list2));
if(count($difference)==0){
echo 'Every item in $list1 is in $list2.';
} else {
echo 'The following numbers are not present in $list2: '.implode(',
',$difference);
}
--
Rik Wasmus

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация