How to properly delete an element from an array in PHP and reindex keys? Problems with unset()
Hello everyone! I'm a beginner in PHP and encountered a problem when deleting elements from an array.
I have an array with user names:
```php
$users = ['Anna', 'Ivan', 'Maria', 'Peter'];
```
I need to delete the second element (Ivan). I read that the `unset()` function is used for this, and wrote the following code:
```php
unset($users[1]);
print_r($users);
```
But the result really surprised me! Instead of an array with three elements (keys 0, 1, 2), I got:
```
Array
(
[0] => Anna
[2] => Maria
[3] => Peter
)
```
The keys became non-sequential: 0, 2, 3. When trying to iterate with `for` using `count($users)`, I skip the element with key 2. I also tried to delete an element by value rather than by key — for example, delete all users with the name "Maria". How can this be done?
No answers yet.
Log in to leave an answer
Blogs