Deleting an element from an array in PHP

后端 未结 30 3270
时光说笑
时光说笑 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条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 06:40

    "value 1", "key2"=>"value 2", "key3"=>"value 3");
    
        print_r($my_array);
        if (array_key_exists("key1", $my_array)) {
            unset($my_array['key1']);
            print_r($my_array);
        }
        else {
            echo "Key does not exist";
        }
    ?>
    
    "value 1", "key2"=>"value 2", "key3"=>"value 3");
        print_r($my_array);
        $new_array = array_slice($my_array, 1);
        print_r($new_array);
    ?>
    
    
        ";
        // To remove first array element to length
        // starts from first and remove two element
        $my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
        print_r($my_array);
        $new_array = array_slice($my_array, 1, 2);
        print_r($new_array);
    ?>
    

    Output

     Array ( [key1] => value 1 [key2] => value 2 [key3] =>
     value 3 ) Array (    [key2] => value 2 [key3] => value 3 )
     Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
     Array ( [key2] => value 2 [key3] => value 3 )
     Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
     Array ( [key2] => value 2 [key3] => value 3 )
    

提交回复
热议问题