Re: Proper way to remove an element from an array

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



At 9:30 PM -0400 7/10/07, Robert Cummings wrote:
On Tue, 2007-07-10 at 21:22 -0400, tedd wrote:
 At 2:23 PM -0700 7/10/07, Dan wrote:
 >I know in some languages there's a right way to remove an element
 >from an array and other ways that will give you problems.
 >
 >In PHP can I just set $arrayname[key] = null?  Or will I then end up
 >with key => null as a value.  I looked on php.net under array
 >functions for a bit and I didn't find any sort of remove element
 >function.  I've just never needed to do this before.
 >
 >- Dan

 Dan:

 After after you delete the element, as Robert suggested with unset(),
 then you can renumber using array_merge() like so:

 $array = array_merge($array);

 Here's an example:

 http://www.webbytedd.com/b/delete-array-element/

Whooooooaa there buddee... should only renumber your indexes if it is
necessary (why waste cycles if it's not) AND your key to value mapping
isn't important (just mentioning this because the noobie might not
understand that it can be very important).

Also array_values() would be the better way to renumber the the array
since it doesn't imply you are doing something else and almost certainly
contains less inernal checks on the input :)

Cheers,
Rob.


Rob:

Good points. I thought the OP said something about renumbering the array so I added a way I found while reading.

As for the time, while it is slower, it's not that much slower -- both are pretty quick.

However, I agree that array_merge() vs array_values() infers something is happening when it's not. So, your solution is better all around.

Cheers,

tedd

--
-------
http://sperling.com  http://ancientstones.com  http://earthstones.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux