PHP array_remove and array_remove_assoc

Thursday, August 25th, 2011

The array_remove and array_remove_assoc PHP functions allow your code to remove an element from an array (or associative array) given the element’s value. See the comments in the code bellow on how to use the two functions.

Download the code

<?php
/**
 * Removes the given value from the given array.
 *
 * Returns either FALSE if the value was not found in the array
 * or the index at which the value was found and removed.
 * 
 * $array = array('a', 'b', 'c', 'd');
 * assert( array_remove( 'b', $array ) == 1 );
 * assert( array( 'a', 'c', 'd' ) == $array );
 * assert( array_remove( 'z', $array ) === false );
 * assert( array( 'a', 'c', 'd' ) == $array );
 *
 * @param mixed $val The value to remove
 * @param array $array The array from which to remove the value
 * @author Dimitry Zolotaryov, http://old.webit.ca
 * @returns FALSE or the index at which the value was found
 */
function array_remove( $val, &$array ) {
    foreach ( $array as $i => $v ) {
        if ( $v == $val ) {
            array_splice( $array, $i, 1 );
            return $i;
        }
    }
    return false;
}
 
/**
 * Removes the given value from the given associative array.
 *
 * Returns either FALSE if the value was not found in the array
 * or the key at which the value was found and removed.
 *
 * $array2 = array( 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4 );
 * assert( array_remove_assoc( 1, $array2 ) == 'a' );
 * assert( array( 'b' => 2, 'c' => 3, 'd' => 4 ) == $array2 );
 * 
 * @param mixed $val The value to remove
 * @param array $array The associative array from which to remove the value
 * @author Dimitry Zolotaryov, http://old.webit.ca
 * @returns FALSE or the index at which the value was found
 */
function array_remove_assoc( $val, &$array ) {
    foreach ( $array as $key => $value ) {
        if ( $value == $val ) {
            unset( $array[ $key ] );
            return $key;
        }
    }
    return false;
}

Download the code

Leave a Reply