Deleting an element from an array in PHP

后端 未结 30 3412
时光说笑
时光说笑 2020-11-21 05:55

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?

I thought that setting it

30条回答
  •  猫巷女王i
    2020-11-21 06:51

    unset() multiple, fragmented elements from an array

    While unset() has been mentioned here several times, it has yet to be mentioned that unset() accepts multiple variables making it easy to delete multiple, noncontiguous elements from an array in one operation:

    // Delete multiple, noncontiguous elements from an array
    $array = [ 'foo', 'bar', 'baz', 'quz' ];
    unset( $array[2], $array[3] );
    print_r($array);
    // Output: [ 'foo', 'bar' ]
    

    unset() dynamically

    unset() does not accept an array of keys to remove, so the code below will fail (it would have made it slightly easier to use unset() dynamically though).

    $array = range(0,5);
    $remove = [1,2];
    $array = unset( $remove ); // FAILS: "unexpected 'unset'"
    print_r($array);
    

    Instead, unset() can be used dynamically in a foreach loop:

    $array = range(0,5);
    $remove = [1,2];
    foreach ($remove as $k=>$v) {
        unset($array[$v]);
    }
    print_r($array);
    // Output: [ 0, 3, 4, 5 ]
    

    Remove array keys by copying the array

    There is also another practice that has yet to be mentioned. Sometimes, the simplest way to get rid of certain array keys is to simply copy $array1 into $array2.

    $array1 = range(1,10);
    foreach ($array1 as $v) {
        // Remove all even integers from the array
        if( $v % 2 ) {
            $array2[] = $v;
        }
    }
    print_r($array2);
    // Output: [ 1, 3, 5, 7, 9 ];
    

    Obviously, the same practice applies to text strings:

    $array1 = [ 'foo', '_bar', 'baz' ];
    foreach ($array1 as $v) {
        // Remove all strings beginning with underscore
        if( strpos($v,'_')===false ) {
            $array2[] = $v;
        }
    }
    print_r($array2);
    // Output: [ 'foo', 'baz' ]
    

提交回复
热议问题