Looping through array

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
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

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 :-)

Re: Looping through array

dennis.sprengers@gmail.com wrote:
Quoted text here. Click to load it

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

Site Timeline