Home > database >  Foreach Loop php - Telegram bot
Foreach Loop php - Telegram bot

Time:06-15

I'm trying to send a single message with some information stored in an associative array but, using foreach, it sends multiple messages, is there a way to send just one?

$users = [
    123 => ["Name 1", "7%", 1],
    456 => ["Name 2", "19.5%", 1],
    789 => ["Name 3", "0%", 0],
];

foreach ($users as $i) {
    sm("$i[0]: $i[1]"); // sm() is a function that sends a message via telegram bot apis
}

CodePudding user response:

You could do something simple like this. Append the text into a single string and then send it once after the loop.

$users = [
    123 => ["Name 1", "7%", 1],
    456 => ["Name 2", "19.5%", 1],
    789 => ["Name 3", "0%", 0],
];

$userlist="";
foreach ($users as $i) {
    $userlist.="$i[0]: $i[1]\n";
}
sm($userlist); // sm() is a function that sends a message via telegram bot apis

CodePudding user response:

$users = [
    123 => ["Name 1", "7%", 1],
    456 => ["Name 2", "19.5%", 1],
    789 => ["Name 3", "0%", 0],
];

$message = implode(PHP_EOL, array_map(fn($i) => "$i[0]: $i[1]", $users));

sm($message);
  • Related