I have a Telegram bot that fetches JSON data from an API when users send a specific command like “FOOD”. The bot should loop through all items in the JSON response and display them, but only the last item appears in the message.
$data = file_get_contents('https://api.restaurant.com/dishes.json');
$items = json_decode($data);
foreach ($items as $item)
{
$message = $item->category;
$message = $message." - ".$item->name;
}
The weird thing is that when I test this same code outside the bot environment, the foreach loop works perfectly and shows all items. But inside the Telegram bot, it only shows the final item from the JSON array. What could be causing this issue?
right on! i had the same issue. you gotta use $message .= to keep adding to it instead of overwriting. and make sure you start with $message = ‘’; before the loop. otherwise, it just shows the last item!
This isn’t a Telegram bot issue - it’s a basic variable assignment mistake. Your foreach loop overwrites $message every time instead of building it up. I hit this same problem building a similar bot last year. Fix it by concatenating with $message .= $item->category." - ".$item->name."\n"; or throw everything into an array first. Don’t forget $message = ''; before the loop. It might seem to work outside the bot because you’re debugging differently, but the logic’s still broken either way.
You’re overwriting the $message variable instead of adding to it. Each loop iteration assigns a new value to $message, so you only get the last item when it’s done. Use .= to concatenate or build an array and implode it later. Change your assignment to $message .= $item->category." - ".$item->name."\n"; and initialize $message as an empty string before the loop. The newline character will separate each item in your Telegram message. This happens whether you’re inside or outside the bot environment - it’s a loop logic issue, not a Telegram problem.