Search code examples
phparrayssearchstrpos

List all elements in array containing certain word in PHP


I'm attempting to make a search feature for my website using PHP. Right now, I have this code to create an array of all files in a directory, which works just fine, but I've hit a snag with my next step. I want it to now list all elements in that array that contain a certain word (the users search), this way I can do something with them later in HTML. My idea was to make a loop that runs strpos for each element and list only the ones it finds matches for. I've tried that, but it always gave me nothing. This is my honest attempt:

<?php
    $search = "Pitfall";

    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $filename)
    {
        if ($filename->isDir()) continue;

        foreach ($filename as &$result)
        {
            $pos = strpos($result, $search);

            if ($pos === true) {
                echo "$result\n";
            } 
        }
    }
?>

Thank you for any help


Solution

  • I think your issue is with your conditional:

    if ($pos === true)

    strpos() does not return true. It returns the position of the string or false. See docs. You could instead use:

    if ($pos !== false)

    Edited:

    The RecusiveIteratorIterator does not return a string. It returns an object. Here I am typecasting the object so that it gets the correct filename. From there, you don't need to iterate over again, as this is just a string at this point.

    $search = "wp-config";
    
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $filename)
    {
        $filename = (string) $filename;
    
        if (is_dir($filename)) continue;
    
        $pos = strpos($filename, $search);
    
        if ($pos !== false) {
            echo "$filename <br />";
        }
    }