Problems with nested array after using unset

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?

Answers


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']);

try

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


Need Your Help

How can I use Template Toolkit on a string instead of a file?

perl template-toolkit

I have some strings that I am pulling out of a database and I would like to use Template Toolkit on them, but I can't seem to figure out how to use strings as TT input. Any tips?

how to sort this multi dimensional array according to following conditions

php arrays sorting

i have an array which is called parentArray() and is an associative array with keys as numbers (not ordered integers) and the values which may be or may not be arrays. I have a foreach() loop which...

What does this typedef really mean?

c++ typedef

typedef const char* Argv[3+ 8];