0

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.

Peter
  • 8,776
  • 6
  • 62
  • 95

1 Answers1

10

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
)
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36