Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mohafiz's avatar

Call API within a loop best practice

I have an API that I want to call many times, say 5 times, the API will respond of either success or failure, I want to try calling the API every time and check if the response is success, if it is, then I will return the result from the API, if not then I will try again until the 5 times completed, then I will return a failure to the client.

Now I am using a while loop to do this, like this

$i = 1;
while($i <= 5){
//call API
//check for success response and return it
$i = $i + 1;
}
//return failure response

I want to know if this will work, and if there is any other 'best practice' to handle this situation ?

0 likes
1 reply

Please or to participate in this conversation.