Deleting an element from an array in PHP

后端 未结 30 3274
时光说笑
时光说笑 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:24

    Destroy a single element of an array

    unset()

    $array1 = array('A', 'B', 'C', 'D', 'E');
    unset($array1[2]); // Delete known index(2) value from array
    var_dump($array1);
    

    The output will be:

    array(4) {
      [0]=>
      string(1) "A"
      [1]=>
      string(1) "B"
      [3]=>
      string(1) "D"
      [4]=>
      string(1) "E"
    }
    

    If you need to re index the array:

    $array1 = array_values($array1);
    var_dump($array1);
    

    Then the output will be:

    array(4) {
      [0]=>
      string(1) "A"
      [1]=>
      string(1) "B"
      [2]=>
      string(1) "D"
      [3]=>
      string(1) "E"
    }
    

    Pop the element off the end of array - return the value of the removed element

    mixed array_pop(array &$array)

    $stack = array("orange", "banana", "apple", "raspberry");
    $last_fruit = array_pop($stack);
    print_r($stack);
    print_r('Last Fruit:'.$last_fruit); // Last element of the array
    

    The output will be

    Array
    (
        [0] => orange
        [1] => banana
        [2] => apple
    )
    Last Fruit: raspberry
    

    Remove the first element (red) from an array, - return the value of the removed element

    mixed array_shift ( array &$array )

    $color = array("a" => "red", "b" => "green" , "c" => "blue");
    $first_color = array_shift($color);
    print_r ($color);
    print_r ('First Color: '.$first_color);
    

    The output will be:

    Array
    (
        [b] => green
        [c] => blue
    )
    First Color: red
    

提交回复
热议问题