Search

Friday, November 14, 2008

Remove element array in php




////////////////////////////////// Lists(Numerical Arrays) /////////////////////////////////

/**

* A small function to remove an element from a list(numerical array)

* Arguments: $arr - The array that should be edited

* $value - The value that should be deleted.

* Returns : The edited array

*/

function array_remove($arr,$value) {

return array_values(array_diff($arr,array($value)));

}



////////////////////////////////// Associative Arrays //////////////////////////////////////

/**

* This function will remove all the specified keys from an array and return the final array.

* Arguments : The first argument is the array that should be edited

* The arguments after the first argument is a list of keys that must be removed.

* Example : array_remove_key($arr,"one","two","three");

* Return : The function will return an array after deleting the said keys

*/

function array_remove_key() {

$args = func_get_args();

$arr = $args[0];

$keys = array_slice($args,1);



foreach($arr as $k=>$v) {

if(in_array($k, $keys))

unset($arr[$k]);

}

return $arr;

}



/**

* This function will remove all the specified values from an array and return the final array.

* Arguments : The first argument is the array that should be edited

* The arguments after the first argument is a list of values that must be removed.

* Example : array_remove_value($arr,"one","two","three");

* Return : The function will return an array after deleting the said values

*/

function array_remove_value() {

$args = func_get_args();

$arr = $args[0];

$values = array_slice($args,1);



foreach($arr as $k=>$v) {

if(in_array($v, $values))

unset($arr[$k]);

}

return $arr;

}

No comments: