Categories
PHP

Delete element from array in PHP

You want to delete an element fom an array?

I propose to you this cimple soultion found in php.net

This functions deletes the given element from a one dimesion array.

Parameters:
$array: Array from where we will delete the element.
$deleteIt: The value we want to delete form the array.
$useOldKeys: If the value is false it would re do the index (From 0, 1, …)
If it is true it will preserve the index

Returns true if deleted, false if not found.

function deleteFromArray(&$array, $deleteIt, $useOldKeys = FALSE)
{
    $key = array_search($deleteIt,$array,TRUE);
    if($key === FALSE)  return FALSE;
    unset($array[$key]);
    if(!$useOldKeys)  $array = array_values($array);
    return TRUE;
}

Normally I don’t say where are the source codes since I do them or I have them since long time a go or I modify them. In this case is C&P.

I hope this is useful as it is for me.