PHP: Delete an element from an array

2018-12-31 01:10发布

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 to null would do it, but apparently it does not work.

标签: php arrays
30条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 01:43
unset($array[$index]);
查看更多
泪湿衣
3楼-- · 2018-12-31 01:43

If you have a numerically indexed array where all values are unique (or they are non-unique but you wish to remove all instances of a particular value), you can simply use array_diff() to remove a matching element, like this:

$my_array = array_diff($my_array, array('Value_to_remove'));

For example:

$my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);

This displays the following:

4
3

In this example, the element with the value 'Charles' is removed as can be verified by the sizeof() calls that report a size of 4 for the initial array, and 3 after the removal.

查看更多
心情的温度
4楼-- · 2018-12-31 01:43

Solutions:

  1. To delete one element, use unset( ):
unset($array[3]);
unset($array['foo']);
  1. To delete multiple noncontiguous elements, also use unset( ):
unset($array[3], $array[5]);
unset($array['foo'], $array['bar']);
  1. To delete multiple contiguous elements, use array_splice( ):
array_splice($array, $offset, $length);

Further explanation:

Using these functions removes all references to these elements from PHP. If you want to keep a key in the array, but with an empty value, assign the empty string to the element:

$array[3] = $array['foo'] = '';

Besides syntax, there's a logical difference between using unset( ) and assigning '' to the element. The first says This doesn't exist anymore, while the second says This still exists, but its value is the empty string.

If you're dealing with numbers, assigning 0 may be a better alternative. So, if a company stopped production of the model XL1000 sprocket, it would update its inventory with:

unset($products['XL1000']);

However, if it temporarily ran out of XL1000 sprockets, but was planning to receive a new shipment from the plant later this week, this is better:

$products['XL1000'] = 0;

If you unset( ) an element, PHP adjusts the array so that looping still works correctly. It doesn't compact the array to fill in the missing holes. This is what we mean when we say that all arrays are associative, even when they appear to be numeric. Here's an example:

// create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1];  // prints 'bee'
print $animals[2];  // prints 'cat'
count($animals);    // returns 6

// unset( )
unset($animals[1]); // removes element $animals[1] = 'bee'
print $animals[1];  // prints '' and throws an E_NOTICE error
print $animals[2];  // still prints 'cat'
count($animals);    // returns 5, even though $array[5] is 'fox'

// add new element
$animals[ ] = 'gnu'; // add new element (not Unix)
print $animals[1];  // prints '', still empty
print $animals[6];  // prints 'gnu', this is where 'gnu' ended up
count($animals);    // returns 6 

// assign ''
$animals[2] = '';   // zero out value
print $animals[2];  // prints ''
count($animals);    // returns 6, count does not decrease

To compact the array into a densely filled numeric array, use array_values( ):

$animals = array_values($animals);

Alternatively, array_splice( ) automatically reindexes arrays to avoid leaving holes:

// create a "numeric" array
    $animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
    array_splice($animals, 2, 2);
    print_r($animals);
    Array
    (
        [0] => ant
        [1] => bee
        [2] => elk
        [3] => fox
    )

This is useful if you're using the array as a queue and want to remove items from the queue while still allowing random access. To safely remove the first or last element from an array, use array_shift( ) and array_pop( ), respectively.

查看更多
无色无味的生活
5楼-- · 2018-12-31 01:44

If you have to delete multiple values in an array and the entries in that array are objects or structured data, [array_filter][1] is your best bet. Those entries that return a true from the callback function will be retained.

$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']]
查看更多
余生无你
6楼-- · 2018-12-31 01:44

Follow default functions

i)

$Array = array("test1","test2","test3","test3");

unset($Array[2]);

ii)

$Array = array("test1","test2","test3","test3");

array_pop($Array);

iii)

$Array = array("test1","test2","test3","test3");

array_splice($Array,1,2);

iv)

$Array = array("test1","test2","test3","test3");

array_shift($Array);
查看更多
君临天下
7楼-- · 2018-12-31 01:47
$key = array_search($needle,$array);
if($key!==false){
    unset($array[$key]);
}
查看更多
登录 后发表回答