skip to Main Content

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
}

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. $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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search