Naming files using list from 0 to Z

O que ando aprendendo nesta caminhada sobre a Terra

Naming files using list from 0 to Z

Today I was coding some scripts and found a little trouble to use a defined pattern.

The pattern is to create files where the sequence starts in 0 (zero) and cannot be repeated until Z.

Example:

myfile0.ext, myfile1.ext, myfile2.ext, (...), myfile9.ext, myfileA.ext, myfileB.txt, (...), myfileZ.txt

Well, this is not a big trouble so I did use this code.

// Filename
$seq = $last_used_seq = '';
$seqs = array_merge(range('0','9'), range('A', 'Z'));]
$l = 1;
while (!in_array($seq, $seqs)) {
    $seq = chr(ord($last_used_seq) + $l++);
}

But

$seq

did not gave the expected value of 0 (zero) on first run. Instead, it was blank.

Debugging the variables, I saw that the while never evaluates to true. Attempting to reproduce on command line I saw that

in_array($seq, $seqs);

always return true. I tryed to use “”, “R” and no matter what value I used, still returning true.

So I change to use STRICT argument for in_array to true and works for ‘A’ through ‘Z’, but not for ‘0’ through ‘9’.

while (!in_array($seq, $seqs, true)) {
    $seq = chr(ord($last_used_seq) + $l++);
}

Damn… PHP is right, “0” is not strictly equals to 0. The Chr function return string and

range('0', '9')

creates an array with integer values.

So, I changed the approach to evaluate all values with STRICT, because I would like to create a nice and clean code without no other functions to be used.

This is the final code that I’m using:

// Initial values 
$seq = '';
$seqs = array_merge(range(ord('0'),ord('9')), range(ord('A'), ord('Z')));
$seqs = array_map('chr', $seqs);
$l = 1;
while (!in_array($seq, $seqs, true)) {
    $seq = chr(ord($infos['last_seq']) + $l++);
}

// Filenames
foreach ($itens_for_files as $key => $itens) {
    // ... Another codes to fill file    
    $seq = chr(ord($seq) + 1);
    while (!in_array($seq, $seqs, true)) {
    $seq = chr(ord($seq) + 1);
    $filename = 'myfile' . $seq . '.ext';
    // ...
}

How you can see, I changed the $seqs initial values from ‘0’ to your ASCII code and get back to your value that gave me an array with all values in string type.

See you!

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.