skip to Main Content

This code snippet:

$inline_keyboard = new InlineKeyboard([
    ['text' => 'valueA', 'callback_data' => 'valueA'],
], [
    ['text' => 'valueB', 'callback_data' => 'valueB'],
]);

produces in my telegramm bot the following inline keyboard:

telegram output

So far so good… But instead of hardcoding the values, I want to produce the same output with values from an array (database query).

I tried with something like this:

$dbValues = array("valueA", "valueB");

foreach ($dbValues as $value)
{
    $inline_keyboard .= new InlineKeyboard([
        ['text' => "$value", 'callback_data' => "$value"],
    ]);
}

But this fails… I think because I don’t have to run a “new” instance in each iteration?

Thanks for helping!

2

Answers


  1. Chosen as BEST ANSWER

    To get a horizontal keyboard you can use this code snippet:

    $dbValues = array("valueA", "valueB");
    foreach ($dbValues as $value)
    {
        $inline_keyboard[] = ['text' => "$value", 'callback_data' => "$value"];
    }
    
    $inline_keyboard = new InlineKeyboard($inline_keyboard);
    

  2. You can’t concatenation object like string. you can go another way, build the array, and after send array to InlineKeyboard

    $dbValues = array("valueA", "valueB");
    foreach ($dbValues as $value)
    {
        $inline_keyboard[] = [['text' => "$value", 'callback_data' => "$value"]];
    }
    
    $inline_keyboard = new InlineKeyboard(...$inline_keyboard);
    

    Further details see “New Keyboard structure and how to pass dynamic arguments” from the php-telegram-bot wiki.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search