0

I want to unset a known value from an array. I could iterate with a for loop to look for the coincident value and then unset it.

<?php

for($i=0, $length=count($array); $i<$length; $i++)
{
   if( $array[$i] === $valueToUnset ) 
        //unset the value from the array
}

Any idea? Any way to achieve it without looping?

Manolo
  • 24,020
  • 20
  • 85
  • 130
  • @Loïc Yeah, I guess I thought it barely deserved an answer, because it was basically pointing at a page the OP could have found pretty easily themselves, but since I then thought of two other solutions, I've put them all into an answer and removed the comments. – IMSoP Mar 18 '14 at 19:19
  • Sorry! I was wrong when I said "extract". Actually, I want to say "unset" the value from the array. I've edited my question. – Manolo Mar 18 '14 at 19:28
  • The edited question is a duplicate of [Removing array item by value](http://stackoverflow.com/questions/1883421/removing-array-item-by-value). (I've removed my downvote since the question is now a lot clearer in its intent and has less trivial solutions.) – IMSoP Mar 18 '14 at 19:32
  • @IMSoP - Yes! `array_diff` seems to be the solution. Thank you and sorry about my confusion. – Manolo Mar 18 '14 at 19:36
  • @ManoloSalsas No problem, and I hope I didn't come across as too harsh. Looking at the answers on that other question, I think I would go with `array_search` or `array_keys` myself, but only as a matter of taste. And `array_filter` is well worth understanding for when you have slightly more complex variations of the same task. – IMSoP Mar 18 '14 at 19:39

2 Answers2

0

I am presuming that your intention is to get the index back, as you already have the value. I am further presuming that there is also a possibility that said value will NOT be in the array, and we have to account for that. I am not sure what you are using array_slice for. So, if I properly understand your requirements, a simple solution would be as follows:

<?php
    $foundIndex = false; //Initialize variable that will hold index value
    $foundIndex = array_search($valueToExtract, $array);
    if($foundIndex === null) {
       //Value was not found in the array
    } else {
       unset($array[$foundIndex];  //Unset the target element
    }
 ?>
Don Briggs
  • 531
  • 2
  • 10
  • 23
  • Note that `array_search()` returns `false` on not found, not `null`; also, the initialization line is useless since the next line is unconditionally assigning over the top of it. – IMSoP Mar 18 '14 at 19:21
  • Sorry! I was wrong when I said "extract". Actually, I want to say "unset" the value from the array. I've edited my question. – Manolo Mar 18 '14 at 19:40
0

array_diff is the solution:

<?php

array_diff($array, array($valueToUnset));

No iteration needed.

Manolo
  • 24,020
  • 20
  • 85
  • 130