function to remove a specified element from an array?

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
oboedrew
Forum Commoner
Posts: 78
Joined: Fri Feb 20, 2009 1:17 pm

function to remove a specified element from an array?

Post by oboedrew »

I'm looking for a function to remove a specified element from an array, but I haven't been able to find one in the php manual.

For example, if I have an indexed array with six elements, how could I remove $array[2] in such a way that $array[3] through $array[5] all drop down a number to fill the gap left behind by the deleted $array[2], leaving an array of five elements?

Seems like this should be common enough, but I can't find a function for it.

Thank,
Drew
asparak
Forum Newbie
Posts: 13
Joined: Tue Feb 24, 2009 3:38 pm

Re: function to remove a specified element from an array?

Post by asparak »

Not 100% sure what you want to do with the array once you have it stripped, but will this do what you need?

Code: Select all

foreach($array as $key => $value) {
if($value == "" || $value == " " || is_null($value)) {
unset($array[$key]);
}
}
/*
and if you want to create a new array with the keys reordered accordingly…
*/
$new_array = array_values($array);
Also found this one on google
Why not just use array_splice?
The script will look like

///////////////////////
//Cleanup array

Code: Select all

for ($i = count($array) - 1; $i >= 0; $i–)
{
if ($array[$i] == “” || $array[$i] == ” ” || is_null($array[$i]))
array_splice($array, $i, 1);
}
//////////////////////////

Should be faster than copying all values from one array to another especially on large arrays.
oboedrew
Forum Commoner
Posts: 78
Joined: Fri Feb 20, 2009 1:17 pm

Re: function to remove a specified element from an array?

Post by oboedrew »

That first suggestion worked perfectly.

Thanks,
Drew
Post Reply