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
function to remove a specified element from an array?
Moderator: General Moderators
Re: function to remove a specified element from an array?
Not 100% sure what you want to do with the array once you have it stripped, but will this do what you need?
Also found this one on google
Why not just use array_splice?
The script will look like
///////////////////////
//Cleanup array
//////////////////////////
Should be faster than copying all values from one array to another especially on large arrays.
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);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?
That first suggestion worked perfectly.
Thanks,
Drew
Thanks,
Drew