3

I'd like to put each file name in $xsl_dir_path (absolute path) in select element. I've tried this:

$files = glob($xsl_dir_path . "/*.xsl");
array_walk($files, 'basename');

but it's not working at all, i can still see the full names of the files. I know i can apply basename when lopping through $files and build the option elements, but i'd like to do it before any html output.

3
  • 1
    glob() will always serve the full file paths. If you don't want that, you need to cut it off afterwards Commented Sep 24, 2011 at 18:21
  • @Pekka i know that, that's why i want to apply basename function to each element of glob array (in an elegant way - meaning i don't like to loop on $files and create a new array). Commented Sep 24, 2011 at 18:25
  • ah, I see. I think that is because basename() doesn't conform with the kind of callback that array_walk() needs - you would have to build a custom function that modifies the first argument directly Commented Sep 24, 2011 at 18:27

3 Answers 3

8

array_walk is useful when your callback function accepts a reference or when you use user-defined callback functions. In this case, the basename argument is not a reference.

What you want is array_map:

$files = glob($xsl_dir_path . "/*.xsl");
$files = array_map('basename', $files);
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

function basename_for_walk (&$value, $key) {
    $value = basename($value);
}
$files = glob($xsl_dir_path . "/*.xsl");
array_walk($files, 'basename_for_walk');

Comments

0

That's because basename() isn't supposed to change the value of the array cells, only to return the new values. You need to pass to array_walk() a function that actually changes the value of the cell. Based on array_walk docs:

function my_basename(&$item)
{
    $item = basaname($item);
}

$files = glob($xsl_dir_path . "/*.xsl");
array_walk($files, 'my_basename');

1 Comment

Works but looks pretty ugly. Thanks anyway!

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.