1

so many ways, we can achieve below expected output, but here intention is, how to use multiple callback in array map and achieve the below expected output.

How to add multiple callback in array_map

<?php
$scandir = scandir('.');
echo "<pre>";
print_r($scandir);
$scandir = array_map('array_filter',array_map('callback',$scandir));
print_r($scandir);

function callback(&$var){
    $curtime  = time();
    $filetime = filemtime($var);
    $diff = $curtime - $filetime;
    if ($diff < 2000){
        return $var;
    }
}
?>

Actual Output

Array
(
    [0] => .
    [1] => ..
    [2] => array.php
    [3] => array.php.bak
    [4] => code-test.php
    [5] => code-test.txt
    [6] => code-test.txt.bak
    [7] => code-test2.php
    [8] => load-file.csv
    [9] => load-file2.csv
)
Array
(
    [0] => 
    [1] => 
    [2] => 
    [3] => 
    [4] => 
    [5] => 
    [6] => 
    [7] => 
    [8] => 
    [9] => 
)

Expected Output

Array
(
    [2] => array.php
    [3] => array.php.bak
)

2 Answers 2

1

It's a bit unclear what you are actually wanting to do, although if the intention is to check for files or directories that have been modified within a certain range from now then making a few adjustments to your code should be adequate:

function callback(&$var) {
    $curtime  = time();
    $filetime = filemtime($var);
    $diff = $curtime - $filetime;
    if ($diff < 2000) {
        return $var;
    }
};

$scandir = scandir('.');
$scandir = array_filter(array_map("callback", $scandir));
print_r($scandir);

Some of the code you have might not be necessary, although I unfortunately can't check it atm.

Sign up to request clarification or add additional context in comments.

3 Comments

intention is, need to work with array map with multiple calllback
You should show your full code since you're only showing one callback.
@Bharanikumar: Can you edit your question to explain what the exact reason you want to use multiple callbacks is though; I think that would be helpful, even for people that might be able to guess.
1

I think the problem is when you call

$scandir = array_map('array_filter',array_map('callback',$scandir));

because you can achieve that by using array_filter function.

The following should works

<?php
$scandir = scandir('.');
echo "<pre>";
print_r($scandir);
$scandir = array_filter($scandir,'callback');
print_r($scandir);

function callback(&$var){
    $curtime  = time();
    $filetime = filemtime($var);
    $diff = $curtime - $filetime;
    if ($diff < 2000 && $var != '.'){
        return $var;
    }
}
?>

Comments

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.