1

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 array will empty...
How can i delete an exact element from the array?
Thank you

5 Answers 5

4

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);
Sign up to request clarification or add additional context in comments.

Comments

4

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]);

Comments

2

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.

Comments

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

Comments

2

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

1 Comment

You should note that this will reorder the index keys, so the resulting array will be 0,1,2 instead of 0,2,3 when just using unset, which is the only reason to use the slower array_splice over unset for this UseCase.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.