Deleting an element from an array in PHP
snippet in php

Deleting an element from an array in PHP

user1262

$key = array_search($needle, $array);
if ($key !== false) {
    unset($array[$key]);
}

Deleting an element from an array in PHP

user5593

unset($array[$index]);

Deleting an element from an array in PHP

user8850

unset($array["elementName"]);

Deleting an element from an array in PHP

user3687

$array = array(3, 9, 11, 20);
$array = array_diff($array, array(11) ); // removes 11

Deleting an element from an array in PHP

user6628

$array = [
    ['x'=>1,'y'=>2,'z'=>3], 
    ['x'=>2,'y'=>4,'z'=>6], 
    ['x'=>3,'y'=>6,'z'=>9]
];

$results = array_filter($array, function($value) {
    return $value['x'] > 2; 
}); //=> [['x'=>3,'y'=>6,z=>'9']]

Deleting an element from an array in PHP

user9373

class obj {
    protected $fields = array('field1','field2');
    protected $field1 = array();
    protected $field2 = array();
    protected loadfields(){}
    // This will load the $field1 and $field2 with rows of data for the column they describe
    protected function clearFields($num){
        foreach($fields as $field) {
            unset($this->$field[$num]);
            // This did not work the line below worked
            unset($this->{$field}[$num]); // You have to resolve $field first using {}
        }
    }
}

Deleting an element from an array in PHP

user3514

if (($key = array_search('word', $array)) !== false) {
    unset($array[$key]);
}

Deleting an element from an array in PHP

user7810

// Remove by value
function removeFromArr($arr, $val)
{
    unset($arr[array_search($val, $arr)]);
    return array_values($arr);
}

php delete element by value

user3868

$colors = array("blue","green","red");

//delete element in array by value "green"
if (($key = array_search("green", $colors)) !== false) {
    unset($colors[$key]);
}

php delete element from array

user4160

//Delete array items with unset(no re-index) or array_splice(re-index)
$colors = array("red","blue","green");                             
unset($colors[1]);//remove second element, do not re-index array

$colors = array("red","blue","green");
array_splice($colors, 1, 1); //remove second element, re-index array

Deleting an element from an array in PHP

user2299

$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]); //Key which you want to delete
/*
$array:
[
    [0] => a
    [2] => c
]
*/
//OR
$array = [0 => "a", 1 => "b", 2 => "c"];
array_splice($array, 1, 1);//Offset which you want to delet
/*
$array:
[
    [0] => a
    [1] => c
]
*/

php remove element from array

user8745

$arr = array('a' => 1, 'b' => 2, 'c' => 3);
unset($arr['b']);

// RESULT: array('a' => 1, 'c' => 3)

$arr = array(1, 2, 3);
array_splice($arr, 1, 1);

// RESULT: array(0 => 1, 1 => 3)