开发者

Delete an (exact) element from an array in php

开发者 https://www.devze.com 2022-12-23 19:03 出处:网络
For example i have an array like this: $test= array(\"0\" => \"412\", \"1\" => \"2\"); I would like to delete the element if its = 2

For example i have an array like this:

  $test= array("0" => "412", "1" => "2"); 

I would like to delete the element if its = 2

 $delete=2;
 for($j=0;$j<$dbj;$j++) {
     if (in_array($delete, $test)) {    
         unset($test[$j]);
     }
 }
 print_r($test);

But with this, unfortunatelly the开发者_StackOverflow array will empty...

How can i delete an exact element from the array?

Thank you


In the loop you're running the test condition is true because $delete exists in the array. So in each iteration its deleting the current element until $delete no longer exists in $test. Try this instead. It runs through the elements of the array (assuming $dbj is the number of elements in $delete) and if that element equals $delete it removes it.

$delete=2;
for($j=0;$j<$dbj;$j++) {
    if ($test[$j]==$delete)) {  
        unset($test[$j]);
    }
}
print_r($test);


What do you mean in exact?

I you would ike to delete element with key $key:

unset($array[$key]);

If specified value:

$key = array_search($value, $array);
unset($array[$key]);


Try

if( $test[$j] == $delete )
    unset( $test[$j] );

What your current code does is search the whole array for $delete every time, and the unset the currently iterated value. You need to test the currently iterated value for equality with $delete before removing it from the array.


$key = array_search(2, $test);
unset($test[$key]);


To delete a specific item from an array, use a combination of array_search and array_splice

$a = array('foo', 'bar', 'baz', 'quux');
array_splice($a, array_search('bar', $a), 1);
echo implode(' ', $a); // foo baz quux
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号