3

Take the following array:

$fruits = [
    'apple', 'banana', 'grapefruit', 'orange', 'melon'
];

Grapefruits are just disgusting, so I would like to unset it.

$key = array_search('grapefruit', $fruit);
unset($fruit[$key]);

The grapefruit is out of my $fruit array but my keys are no longer numbered correctly.

array(4) {
    [0] => 'apple'
    [1] => 'banana'
    [3] => 'orange'
    [4] => 'melon'
}

I Could loop through the array and create a new one but I was wondering if there's a simpler method to reset the keys.

5
  • There is.... array_values() Commented Oct 6, 2017 at 9:13
  • 1
    3.5k rep and I found your duplicate target by just googling "php reset array keys" Commented Oct 6, 2017 at 9:14
  • 1
    @Epodax You could have looked in the Related bar as well :-) Commented Oct 6, 2017 at 9:15
  • 1
    @jeroen Only makes it that much worse for OP. Commented Oct 6, 2017 at 9:15
  • What I use in similar situations is $arr = array_merge( $arr );. You can see my answer to a similar question, stackoverflow.com/a/55048335/673846. Commented Mar 28, 2019 at 13:58

1 Answer 1

15

Use array_values()

array_values( $array );

Test Results:

[akshay@localhost tmp]$ cat test.php
<?php

$fruits = [
    'apple', 'banana', 'grapefruit', 'orange', 'melon'
];

$key = array_search('grapefruit', $fruits);
unset($fruits[$key]);

// before
print_r($fruits);

//after
print_r(array_values($fruits));
?>

Execution:

[akshay@localhost tmp]$ php test.php
Array
(
    [0] => apple
    [1] => banana
    [3] => orange
    [4] => melon
)
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => melon
)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.