You are here: Re: Looping through array « PHP Programming Language « IT news, forums, messages
Re: Looping through array

Posted by Curtis on 02/23/07 01:48

dennis.sprengers@gmail.com wrote:
> Consider the following array and string:
>
> $trail = array('products/veggies', 'products', 'services/cleaning');
> $path = 'products/veggies/1243/more';
>
> I am trying to write a function that matches $path with a value in
> $trail. If no match is found, it should chop off "more" and compare
> again. Then, chop off "1243" and compare again. Now a match is found:
> "products/veggies". The function should return true.
>
> Let's take another example: $path = 'services/industrial/gardening'.
> There is no match for $path in $trail. Chopping off "gardening" leaves
> "services/industrial". Again, no match. Chopping off "industrial"
> leaves "services". No match will be found; the function should return
> false.
>
> This is what I have so far:
>
> function in_trail($path) {
> global $trail;
>
> while ($path && !in_array($path, $trail)) {
> $path = substr($path, 0, strrpos($path, '/'));
> }
>
> return $path ? true : false;
> }
>
> But this function always returns true! Could someone explain this to
> me and tell me how to fix it? Your help is much appreciated :-)
>

I changed it up a little, the function I wrote passes the string by
reference and uses recursion.

// returns true on success, false on failure
// $path is altered in the calling scope
// remove the reference operator (&) if you'd
// rather that not happen
function in_trail($trail, &$path) {
if ( in_array($path, $trail) ) {
return true;
}
else {
// we can't reduce string anymore
if ( ($idx = strrpos($path, '/')) === false )
return false;

// truncate last dir
$path = substr($path, 0, $idx);

// use recursion to check new dirs
return in_trail($trail, $path);
}
}

I haven't tested this on a wide variety of strings/arrays, but it did
work with your example vars.

Hope it helps.

Curtis, http://dyersweb.com

 

Navigation:

[Reply to this 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

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