Page 1 of 1

how to delete array element with shifting the indexes ??

Posted: Tue Apr 22, 2008 4:23 am
by PHPycho
hello forums!!
Can anybody suggest in the following case:
How to remove an element from an index array and reseting its indexes?
Example:

Code: Select all

$array = array('x', 'y', 'z',..);
unset($array[1]);
print_r($array); // results: 0 => x, 2 => z ,which doesn't reset the indexes
// I would like to have the result as : 0 => x, 1 => z , ie rearraning the indexes
How to accomplish this ?
Thanks in advance for the suggestions.

Re: how to delete array element with shifting the indexes ??

Posted: Tue Apr 22, 2008 6:13 am
by aceconcepts
There is plenty fo help in the php manual. I always refer to the manual first.

Re: how to delete array element with shifting the indexes ??

Posted: Tue Apr 22, 2008 7:16 am
by John Cartwright
I usually use apply an array_values() to reset the keys, although it usually isn't neccesary.

Code: Select all

 
$array = array('x', 'y', 'z',..);
unset($array[1]);
$array = array_values($array);
 

Re: how to delete array element with shifting the indexes ??

Posted: Tue Apr 22, 2008 7:17 am
by PHPycho
Here is the solution:

Code: Select all

 
 $array = array('x', 'y', 'z');
unset($array[1]);
array_values($array);
echo '<pre>';
 print_r($array) ;
echo '</pre>';