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.

Link to comment
Share on other sites

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>';
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.