John Davidson

PHP - best practice to call a function twice with a different param

0 comments
Message:


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



My Answer:
= $maxIds; $i++) {_
$id = $idArray[$i];
$relevantId = getRelevantId($id, $xml, $idType);
// do something with $relevantId
}
}

_What is the best practice to call the `getRelevantId` function twice with a different parameter in the `sortRelevantId` function?_

The best practice would be to create a separate function that calls `getRelevantId` with the different parameter values. This way, you can avoid duplicating code and make your code more maintainable.

Here's an example of how you can refactor the `sortRelevantId` function to call `getRelevantId` with different parameters:

php
function sortRelevantId($idArray, $maxIds, $xml, $idType) {
for ($i = count($idArray); $i < $maxIds; $i++) {
$id = $idArray[$i];
$relevantId1 = getRelevantId($id, $xml, $idType);
$relevantId2 = getRelevantId($id, $xml, $idType2); // assuming $idType2 is a different parameter value
// do something with $relevantId1 and $relevantId2
}
}


In this example, I added a new parameter `$idType2` to the `sortRelevantId` function and called `getRelevantId` with this new parameter value. This way, you can call the `getRelevantId` function twice with different parameters without duplicating code.

Rate this post

3 of 5 based on 8377 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us