How to insert a new element into an array at any position in PHP?
Hello everyone! I'm a beginner in PHP and ran into a problem while working with arrays. I need to insert a new element into an array at an arbitrary position, not just add it to the beginning or end.\n\nHere's an example: I have an array of users:\n\n```php\n$users = ['Anna', 'Boris', 'Victor'];\n```\n\nI want to insert the new name 'Gleb' after 'Boris' to get:\n\n```php\n// ['Anna', 'Boris', 'Gleb', 'Victor']\n```\n\nI tried using `array_push()` — it only adds to the end. `array_unshift()` — only to the beginning. And there's no function like `array_insert()` in PHP.\n\nI've heard about `array_splice()`, but I don't fully understand how to use it. Is there another way? For example, splitting the array into two parts, inserting the element, and then merging? But that seems too cumbersome.\n\nPlease advise
No answers yet.
Log in to leave an answer
Blogs