-1

I want to be able to get a value from anywhere in my array, unset it, and shift the index so that my array indices are still in order.

Original array:

array:3 [
    0 => 'apple'
    1 => 'banana'
    2 => 'orange'
    3 => 'grapes'
]

Get the value of index 1, unset, and shift:

$val = 'banana';

array:2 [
    0 => 'apple'
    1 => 'orange'
    2 => 'grapes'
]

Is there a native PHP function similar to array_pop() or array_shift() that can do this?

Chey Luna
  • 60
  • 1
  • 1
  • 8

3 Answers3

1

You can use array_values for that like as

$array = [
    0 => 'apple',
    1 => 'banana',
    2 => 'orange',
    3 => 'grapes'
];

unset($array[1]);

print_r(array_values($array));
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
1

you will have to create a custom function

function removeAndreindex($array,$index)
 {
    unset($array[$index]);
    return array_values($array)
 }

Thanks

Edy0
  • 54
  • 7
0

Try this:

unset($array[array_search($val, $array)]);

The function array_search will return the index of the value $val, then you can remove it from the array by using unset() function.

Mohammad
  • 3,449
  • 6
  • 48
  • 75