Reputation: 424
Using Amazon's SQS and their PHP SDK I am receiving messages and deleting them just fine however if no messages are received I get an error when attempting to loop through the messages. If there was a way to check the number of messages prior to my foreach statement I would avoid any errors. Obviously I can suppress the error and everything will proceed without a problem but I'd prefer not to.
$result = $sqs->receiveMessage(array(
'QueueUrl' => SQS_QUEUE,
'MaxNumberOfMessages' => 10 ));
foreach ($result->get('Messages') as $message) {
if (process_sqs($message['Body'])) {
$deletemessage = $sqs->deleteMessage(array(
'QueueUrl' => SQS_QUEUE,
'ReceiptHandle' => $message['ReceiptHandle']));
}
}
Basically after the $result is populated I would like to query the number of messages received, if over 0 then proceed to the foreach statement.
I know I could use GetQueueAttributes prior to receiveMessage to get an estimate of the number of messages in the queue but I see no need to make an additional request while not guaranteeing I will actually receive any messages.
Thanks
Upvotes: 1
Views: 1648
Reputation: 5150
You can use PHP to count your array before looping through it with the count() function:
$messages = $result->get('Messages');
if (count($messages) > 0) {
foreach ...
}
Upvotes: 1