1

I'm trying to make a list of directories from a file. But I only want the list to contain unique entries i.e. - only echo once no duplicates.

Example: From this log file:

inactive : [2007-04-01 08:42:21] "home/club/member" 210.00 "r-200"
inactive : [2008-08-01 05:02:20] "home/club/staff" 25.00 "r-200"
active : [2010-08-11 10:12:20] "home/club/member" 210.00 "r-500"
inactive : [2010-01-02 11:12:33] "home/premier/member" 250.00 "r-200"
active : [2013-03-04 10:02:30] "home/premier/member" 250.00 "r-800"
active : [2011-09-14 15:02:55] "home/premier/member" 250.00 "r-100"

I want to echo the list of directories but no duplicates:

home/club/staff

home/club/member

home/premier/member

I used a foreach loop to iterate through the array but I don't know how to compare each value to each item in the array and then only output identical items once.

foreach($listofDir as $value) 
{
    echo "<p>" . $value .  "</p>";
}
1

1 Answer 1

1

This should work for you:

Just get your file into an array and then grab the paths out of each line.

<?php

    $lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    $directorys = array_unique(array_map(function($v){
        preg_match("/.*? : \[.*?\] \"(.*?)\"/", $v, $m);
        return $m[1];
    }, $lines));

    print_r($directorys);

?>

output:

Array
(
    [0] => home/club/member
    [1] => home/club/staff
    [3] => home/premier/member
)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, which part of that script ensures I'm not outputting an identical value?
@MauriceGreenland array_unique() So that you only have unique values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.