Avatar ·

How to add an element to a PHP array with a key and value

Hello everyone! I just started learning PHP and encountered a problem when working with arrays. I need to add an element to an array by specifying both a key and a value. I know that for regular addition without a key, you can use `$array[] = 'value';` — this adds an element with a numeric index. But what should I do if I want, for example, to create an associative array with specific keys?\n\nHere's an example of my situation. I have a form on a website where the user enters a product name and its price. I want to save this in an array where the key is the product name and the value is the price. I tried this:\n\n```php\n$products = [];\n$products[] = 'apple' => 150;\n```\n\nBut this gives a syntax error. Then I tried:\n\n```php\n$products = [];\n$products['apple'] = 150;\n```\n\nThis works, but if I have m