Question

I have a dynamically built nested array from which i need to drop one or more indexes.

Having scoured the php information pages, i found that using

unset($quotes_array[0]['methods'][3]);

would remove the last set of data in the array.

But, if i try to use

unset($quotes_array[0]['methods'][0]);

or any other set apart from the last, it messes up the output that is generated from the array.

For instance, if i had a,b,c,d: I can remove d without issue, but if i try to remove a, i get a blank radio button followed by b,c, with d missing all together when the array data is processed.

I am assuming i need to reindex the array, but every attempt i've made so far has failed to give the required results, most likely because i'm reindexing $quotes_array, whereas the data i actually need to reindex is that within the 'methods' indices.

Is there a way to fix this issue?

Was it helpful?

Solution

unsetting the first element is easy if you use array_shift. array_shift will pop the first element off and reindex your array for you.

array_shift($quotes_array[0]['methods']);

if you need to unset something in the middle (such as [ 2 ] out of [ 3 ]) you could use array_values. First unset the element you want to remove, then reindex them with array_values.

unset($quotes_array[0]['methods'][2]);
array_values($quotes_array[0]['methods']);

if you wanted to remove the last element of an array you could use array_pop. array_pop will pop the last element off the array. There is no need to reindex in this situation.

array_pop($quotes_array[0]['methods']);

OTHER TIPS

try

array_values($quotes_array[0]['methods']);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top