phparraysfilenames

Assign array key based on the trailing number of a filename string


I have a function that retrieves file names in some directory. The directory has multiple PDF files.

I want to assign a key to each of the PDF files I gathered, where the key is the number that is located between - and .pdf in the filename.

For instance I have 3 PDF files:

abc-1.pdf
abc-2.pdf
abc-3.pdf

What I want to have:

1 => abc-1.pdf,
2 => abc-2.pdf,
3 => abc-3.pdf

My function is currently this:

function getPDFs($PDF_DIR_NAME, $PDF_TOKEN) {
    if ($PDF_TOKEN == null || $PDF_TOKEN == '') {
        return null;
    } else {
        $getPDFVersions = $PDF_TOKEN.
        "*";
        $dirs = glob($PDF_DIR_NAME.
            '/'.$getPDFVersions);
        $files = array();
        foreach($dirs as $d) {
            if (filesize($d) > 200) {
                $files[] = basename($d);
            }
        }
        return $files;
    }
}

How can I assign keys for each PDF document?


Solution

  • Ingredients:

    1. strrchr(): Find the last occurrence of a character in a string
    2. substr(): Return part of a string
    3. (int) - Cast to integer (if required)

    Recipe:

    1. Find the position of the (last) dash (-), as it comes before the ID.
    2. Find the position of the (last) dot (.), as it comes after the ID (see below)
    3. Strip out the ID with substr() and the information gathered in step 1 (and 2)
    4. Optionally, use the IDs to populate an associative array, like so:

      $myPDFs = array();
      $myPDFs[$id] = $filename;
      

    Or whatever it is you need.

    PS:

    Instead of finding the position of the last dot, you could also simply assume that it is always 4 characters before the end of the filename. Seems a safe bet. Hint: substr() can take a negative number as its start parameter.