-2

I need to repeat a small piece of code several times so wrote a function which does not work, but when written outside of a function the code does work. I'm doing something daft but just can't see what it is!! Can someone please tell me how daft I am. Thank you.

This does not work:

function listfiles()
{$count=count($file);
for($z=0; $z<$count; $z++)
{$parts=explode("/",$file[$z]);
$parts=explode(".",$parts[1]);
print"<a href='$file[$z]'>$parts[0]</a><br><br>";}}

$file=glob("/xxx/xxx/files/*.*");
listfiles();

Yet this does:

$file=glob("/xxx/xxx/files/*.*");
{$count=count($file);
for($z=0; $z<$count; $z++)
{$parts=explode("/",$file[$z]);
$parts=explode(".",$parts[1]);
print"<a href='$file[$z]'>$parts[0]</a><br><br>";}}
Roy Cole
  • 1
  • 1
  • 1
    [Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – Funk Forty Niner Nov 06 '17 at 15:43
  • place the `$file=glob("/xxx/xxx/files/*.*");` inside the function – Funk Forty Niner Nov 06 '17 at 15:47
  • Your code is formatted in a way that makes it very hard to read. – GrumpyCrouton Nov 06 '17 at 15:55
  • Grumpy, I apologise for my unconventional style. I began learning to code with Fortran in 1967. It wasn’t until – Roy Cole Nov 07 '17 at 07:18
  • Grumpy, It wasn't until 1982 that I could afford a computer and switched to IBM basic. Wrote some commercial stuff but coding has only ever been a self taught hobby. Switched to php when I retired and was asked to build a website. So apologies again for my style, old habits die hard and at 67 it's old dogs and new tricks !! – Roy Cole Nov 07 '17 at 13:55
  • Fred -ii-, Thank you for the link, very helpful. Always good to learn. – Roy Cole Nov 07 '17 at 13:57

1 Answers1

0

Give the $file variable as an argument

function listfiles($file)
{
    $count=count($file);
    for($z=0; $z<$count; $z++)
    {
        $parts=explode("/",$file[$z]);
        $parts=explode(".",$parts[1]);
        print"<a href='$file[$z]'>$parts[0]</a><br><br>";
    }
}

$file=glob("/xxx/xxx/files/*.*");
listfiles($file);
Saphyra
  • 450
  • 3
  • 15