unset in php array code example

Example 1: php delete element by value

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

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

Example 2: php remove item array

$items = ['banana', 'apple'];

unset($items[0]);

var_dump($items); // ['apple']

Example 3: php unset array key

unset($dataArray['key']);

Example 4: php delete element from array

//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

Example 5: php erase element from array

foreach ($items as $key =>$item){
  if(condition){
    unset($item[$key]);
  }
}

Example 6: unset by key name php

unset($array['key-here']);

Tags:

Php Example