In this post we will discuss to reset an array after add or delete an index.
If there are an array
Now we updates this array and delete
Index 2 has been removed from array and we have to re-arrange all indexes of array.
So its not a big task. Just a simple step and array will arrange form index 0 to 3.
Use the predefined array function
This was a simple array. If we have a multi-dimensional array, Then !!.
Nothing to worry about multi-dimensional, PHP have all tricky solutions :)
To reset multidimensional array use array_map.
Here
Hope this will help you.
If there are an array
$a
$a = array( 0 => 3, 1 => 5, 2 => 7, 3 => 9, 4 => 0 );
Now we updates this array and delete
index 2
, so the new array is -unset($a[2]); $a = array( 0 => 3, 1 => 5, 3 => 9, 4 => 0 );
Index 2 has been removed from array and we have to re-arrange all indexes of array.
So its not a big task. Just a simple step and array will arrange form index 0 to 3.
Use the predefined array function
array_values
and the array indexes will be reset.$a = array_values($a); $a = array( 0 => 3, 1 => 5, 2 => 9, 3 => 0 );
This was a simple array. If we have a multi-dimensional array, Then !!.
Nothing to worry about multi-dimensional, PHP have all tricky solutions :)
$reset_array = array_map('array_values', $arr);
To reset multidimensional array use array_map.
Here
$arr
is a multidimensional array with different indexes and $rest_array
is output after reset all indexes.Hope this will help you.
Comments
Post a Comment