Search code examples
phpcallbackarray-map

array_map two callback functions as one


Here is my codes:

$sc = 'hello 8491241 some text 6254841 some text 568241 414844:412';
preg_match_all('/[0-9]{5,10}/', $sc, $matches1);
preg_match_all('/[0-9]{5,10}:[0-9]{1,5}/', $sc, $matches2);

function cub1($match)
{

    return array(
      'batch' => $match,
      'type' => '1',
    );

}

function cub2($match)
{
    return array(
      'batch' => $match,
      'type' => '2',
    );
}

$pr_matches1 = array_map('cub1', $matches1[0]);
$pr_matches2 = array_map('cub2', $matches2[0]);

$all_matches = array_merge($pr_matches1,$pr_matches2);

It just works fine, i'm asking about if it possible to improve my codes and make the array_map callback functions (cub1 and cub2) as one function (cub), i just need to set different 'types' for $matches1 and $matches2

Any idea please?


Solution

  • Yes it is possible, it's just a little bit tricky to identify in the function from which array it comes. But this should work for you:

    (Here I just use strpos() to identify if it is a match form $matches1 or from $matches2, since only the second array can contain :)

    <?php
    
        $sc = 'hello 8491241 some text 6254841 some text 568241 414844:412';
        preg_match_all('/[0-9]{5,10}/', $sc, $matches1);
        preg_match_all('/[0-9]{5,10}:[0-9]{1,5}/', $sc, $matches2);
    
        function cub($m) {
    
            if(strpos($m, ":") !== FALSE) {
                return array(
                  'batch' => $m,
                  'type' => '2',
                );
            } else {
                return array(
                  'batch' => $m,
                  'type' => '1',
                );
            }
    
    
        }
    
        $all_matches = array_map("cub", array_merge($matches1[0], $matches2[0]));
        print_r($all_matches);
    
    ?>
    

    Output:

    Array ( [0] => Array ( [batch] => 8491241 [type] => 1 ) [1] => Array ( [batch] => 6254841 [type] => 1 ) [2] => Array ( [batch] => 568241 [type] => 1 ) [3] => Array ( [batch] => 414844 [type] => 1 ) [4] => Array ( [batch] => 414844:412 [type] => 2 ) )