Jump to content

Remove Element From current position in array


HardCoreMore

Recommended Posts

Hi all,

 

Is there a function or method to delete element from current position in array without knowing the index. For example:

 

 


$ar = array( 1, 2, 3, "test", 4, 5, "test2" );

while( $v  = current( $ar ) )
{
    if( key( $ar ) == "test" )
     {
          // remove element from the array where key equals "test"
          // i could count every cycle and splice from that index but i wonder can that be done without it
          // i am looking at the php array functions but i can't find any that will delete from element from current position in array

          echo 'key( $ar ) je test. key( $ar ): ' . key( $ar );
     }

      next( $ar );
}

 

 

One thing that i don't understand is that when i run example above the "test" key is found and when i echo it it gives me 0.

Do you mean like this? From your description, I think something like this will work for what you are trying to do.

 

<?php
$ar = array( 1, 2, 3, "test", 4, 5, "test2" );
$value = 'test';

foreach( $ar as $k => $v ) {
     if( $v == $value ) {
          unset( $ar[$k] );
     }
}

echo '<pre>';
print_r($ar);
echo '</pre>';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.