how to delete array element with shifting the indexes ??

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

how to delete array element with shifting the indexes ??

Post 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.
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

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

Post by aceconcepts »

There is plenty fo help in the php manual. I always refer to the manual first.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

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

Post 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);
 
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

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

Post 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>';  
 
Post Reply