Page 1 of 1

function to remove a specified element from an array?

Posted: Thu Feb 26, 2009 2:31 pm
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

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

Posted: Thu Feb 26, 2009 2:35 pm
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.

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

Posted: Tue Mar 03, 2009 1:11 pm
by oboedrew
That first suggestion worked perfectly.

Thanks,
Drew