Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove element from array and reindex from 0

Tags:

arrays

php

Array (
    [REF_DETAILS] = Array
        (
            [0] = Array
                (
                    [ID] => 1231312
                    [USER] => USER
                )

            [1] = Array
                (
                    [TID] => 2754042         
                    [USER] = USER
                )
            [1] = Array
                (
                    [TID] => 534535         
                    [USER] = USER
                )

        )

    [TOTAL_COUNT] = 31
)

I have a array output like this above and I want to remove one element from the array then again i want to reindex it from 0. I tried with array_value in php but after doing this it is removing [REF_DETAIL] with 0 and TOTAL_COUNT as 1 , please provide the solution in php

like image 327
vishalg Avatar asked Sep 01 '12 07:09

vishalg


People also ask

How do I reindex an array?

The re-index of an array can be done by using some inbuilt function together. These functions are: array_combine() Function: The array_combine() function is an inbuilt function in PHP which is used to combine two arrays and create a new array by using one array for keys and another array for values.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

Why is array indexing o1?

This is done in O(1) because it is pretty simple (constant number of math calculations) where the element is located given the index, the beginning of the array and the size of each element.

What is the most efficient way to remove an element from an array?

Most efficient way to remove an element from an array, then reduce the size of the array.


Video Answer


2 Answers

Use array_splice (php docs), it automatically reindexes.

array_splice($array['REF_DETAILS'], 1, 1)

like image 186
Barmar Avatar answered Oct 17 '22 04:10

Barmar


try

unset($array['REF_DETAILS'][1]);
$array['REF_DETAILS'] = array_values($array['REF_DETAILS']);
like image 4
Kasia Gogolek Avatar answered Oct 17 '22 05:10

Kasia Gogolek