Home > front end >  PHP - best practice to call a function twice with a different param
PHP - best practice to call a function twice with a different param

Time:08-17

I have the following function:


function sortRelevantId($idArray, $maxIds, $xml, $idTpe)
{
    for ($i = count($idArray); $i < $maxIds; $i  ) {
        if ($xml->sub[$i]->type == $idTpe) {
            $idArray[] = $i;
        }
    }
    return $idArray;
}



I call these like so, 
$idArray = [];
$idArray= sortRelevantId($idArray , $maxIds, $xml, "a");
$idArray= sortRelevantId($idArray , $maxIds, $xml, "b");

I am wondering how I can change the function so that I only need to call the function one and the logic in the function after type "a" and recall/ reruns for type "b" ("a" takes priority over "b")

Thanks for any help

CodePudding user response:

You can change your codes as below.

function sortRelevantId($idArray, $maxIds, $xml, array $idTpe)
{
    $idArray = array();
    for ($i = count($idArray); $i < $maxIds; $i  ) {
      foreach($idTpe as $item) {
        if ($xml->sub[$i]->type == $item) {
            $idArray[] = $i;
        }
      }
    }
    return $idArray;
}

$idArray= sortRelevantId($idArray , $maxIds, $xml, array("a","b"));

CodePudding user response:

You can use array_reduce for this by passing output of one result as input to the other and finally returning the value.

<?php

$idArray = array_reduce(["a", "b"], fn($carry, $item) => sortRelevantId($carry, $maxIds, $xml, $item), []);

print_r($idArray);
  •  Tags:  
  • php
  • Related