如何从php中的非关联数组中删除元素

时间:2022-08-26 14:07:17

I'm trying to remove specific element from php array with unset function. Problem is that when I var_dump array it shows all indexes (not good) but If I try to var_dump specific index PHP throws warning (good).

我正在尝试使用unset函数从php数组中删除特定元素。问题是当我在var_dump数组中它显示所有索引(不好)但是如果我尝试var_dump特定索引PHP抛出警告(好)。

$a = [
    'unset_me',
    'leave_me',
    'whatever',
];

unset($a['unset_me']);

var_dump($a);
/**
array(3) {
  [0]=>
  string(8) "unset_me"
  [1]=>
  string(8) "leave_me"
  [2]=>
  string(8) "whatever
*/
var_dump($a['unset_me']); // Undefined index: unset_me

Question is why php behave like this and how to remove index properly?

问题是为什么php表现得像这样以及如何正确删除索引?

3 个解决方案

#1


3  

You can try this with array_search -

你可以用array_search试试这个 -

unset($a[array_search('unset_me', $a)]);

If needed then add the checks like -

如果需要,然后添加支票,如 -

if(array_search('unset_me', $a) !== false) {
    unset($a[array_search('unset_me', $a)]);
}

Demo

演示

#2


3  

One more solution:

还有一个解决方案

$arr = array('unset_me','leave_me','whatever',);  
print_r($arr);

// remove the elements that you want  
$arr = array_diff($arr, array("unset_me"));
print_r($arr);  

#3


1  

$arr = array('unset_me','leave_me','whatever',);  
print_r($arr);
echo '<br/>';

$key = array_search('unset_me', $arr);
if($key !== false)
unset($arr[$key]);

print_r($arr);

#1


3  

You can try this with array_search -

你可以用array_search试试这个 -

unset($a[array_search('unset_me', $a)]);

If needed then add the checks like -

如果需要,然后添加支票,如 -

if(array_search('unset_me', $a) !== false) {
    unset($a[array_search('unset_me', $a)]);
}

Demo

演示

#2


3  

One more solution:

还有一个解决方案

$arr = array('unset_me','leave_me','whatever',);  
print_r($arr);

// remove the elements that you want  
$arr = array_diff($arr, array("unset_me"));
print_r($arr);  

#3


1  

$arr = array('unset_me','leave_me','whatever',);  
print_r($arr);
echo '<br/>';

$key = array_search('unset_me', $arr);
if($key !== false)
unset($arr[$key]);

print_r($arr);