How to add elements to an empty array in PHP?
Hello everyone! I just started learning PHP and encountered a problem. I need to create an empty array and then dynamically add elements to it as I process data. For example, I have a list of items, and I want to collect only those with a price greater than 100 rubles.\n\nI wrote this code:\n\n```php\n$filtered_items = array();\nforeach ($items as $item) {\n if ($item['price'] > 100) {\n // Here I don't know how to correctly add an element\n }\n}\n```\n\nI tried writing `$filtered_items[] = $item;` and `array_push($filtered_items, $item);` — both options seem to work, but I don't understand the difference and which method is more correct. I also heard that you can use `array_push` with multiple elements at once. I'm also interested in whether it's possible to add elements not to the end, but to the beginning.
No answers yet.
Log in to leave an answer