tags:

views:

84

answers:

5

Hi Masters!

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

+3  A: 

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);
thetaiko
+2  A: 

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.

Andy
+2  A: 
$key = array_search(2, $test);
unset($test[$key]);
Tom
+3  A: 

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]);
alex shishkin
+2  A: 

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
stereofrog
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.
Gordon