12

Here is print_r output of my array:

Array
(
[0] => stdClass Object
    (
        [itemId] => 560639000019
        [name] => Item no1
        [code] => 00001
        [qty] => 5
        [id] => 2
    )

[1] => stdClass Object
    (
        [itemId] => 470639763471
        [name] => Second item
        [code] => 76347
        [qty] => 9
        [id] => 4
    )

[2] => stdClass Object
    (
        [itemId] => 56939399632
        [name] => Item no 3
        [code] => 39963
        [qty] => 6
        [id] => 7
    )

)

How can I find index of object with [id] => 4 in order to remove it from array?

1
  • Weird thing that after unsetting array item, it breaks json_encode so output becomes unusable. Commented Jul 18, 2012 at 12:29

11 Answers 11

15
$found = false;  
foreach($values as $key => $value) {
    if ($value->id == 4) {
        $found = true;
        break;
    }
}

if ($found) unset($values[$key]);

This is considered to be faster then any other solution since we only iterate the array to until we find the object we want to remove.

Note: You should not remove an element of an array while iterating so we do it afterwards here.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm not sure about the rule of not removing array element while iterating it. In another question users were pointing that it is perfectly fine to do so in PHP, so any source on that? Because so far nobody really pointed the reason, just stated it.
for me it was giving error of object not found so i did it as $value['id']
@MarcinSzulc like 500 years ago, PHP threw an exception if you did that. Thats why people (me, too) have a barrier in the brain for doing so ;-)
9
foreach($parentObj AS $key=>$element){
  if ($element->id == THE_ID_YOU_ARE_LOOKING_FOR){
    echo "Gottcha! The index is - ". $key;
  }
}

$parentObj is obviously your root array - the one that holds all the others.

We use the foreach loop to iterate over each item and then test it's id property against what ever value you desire. Once we have that - the $key that we are on is the index you are looking for.

5 Comments

wait .. $element is not an object?
@lax - I don't follow...What do you mean? The variable $element refers to an element within the array...
$element is an instance of stdClass. See the question
@lax - I think I see what you mean - its the way you access the property. I've used the same method as an associative array... My OO PHP is not that strong... but thanks for the comment. A little more explanation would have gone a long way though...
@Lix thanks, your answer is also great. I picked other one only because I had to pick one and that was more "complete".
3

use array_search:

$a = new stdClass;
$b = new stdClass;
$a->id = 1;
$b->id = 2;

$arr = array($a, $b);
$index = array_search($b, $arr);

echo $index;
// prints out 1

Comments

1

try this

foreach($array AS $key=>$object){
   if($object['id'] == 4){
       $key_in_array = $key;
   }
}

// chop it from the original array
array_slice($array, $key_in_array, 1);

1 Comment

This is almost exactly opposite of what I want :)
0

Another way to achieve the result is to use array_filter.

$array = array(
    (object)array('id' => 5),
    (object)array('id' => 4),
    (object)array('id' => 3)
);
$array = array_filter($array, function($item) {
    return $item->id != 4;
});
print_r($array);

2 Comments

This is a good solution, however you are iterating over the whole collection although it is not necessary most of the times.
True, it depends on the situation and certainty of how many elements are there to unset. Though very useful function.
0

Here's my solution. Given, it is a bit hackish, but it will get the job done.

search(array $items, mixed $id[, &$key]);

Returns the item that was found by $id. If you add the variable $key it will give you the key of the item found.

function search($items, $id, &$key = null) {
  foreach( $items as $item ) {
    if( $item->id == $id ) {
      $key = key($item);
      return $item;
      break;
    }
  }

  return null;
}

Usage

$item = search($items, 4, $key);
unset($items[$key]);

Note: This could be modified to allow a custom key and return multiple items that share the same value.

I've created an example so you can see it in action.

Comments

0

A funny alternative

$getIdUnset = function($id) use ($myArray)
{
    foreach($myArray as $key => $obj) {
        if ($obj->id == $id) {
            return $key;
        }
    }

    return false;
};

if ($unset = $getIdUnset(4)) {
    unset($myArray[$unset]);
}

Comments

0

Currently php does not have any supported function for this yet.

So refer to Java's Vector, or jQuery's $.inArray(), it would simply be:

public function indexOf($object, array $elementData) {
    $elementCount = count($elementData);
    for ($i = 0 ; $i < $elementCount ; $i++){
        if ($object == $elementData[$i]) {
            return $i;   
        }
    }
    return -1;
}

You can save this function as a core function for later.

Comments

0

In my case, this my array as $array
I was confused about this problem of my project, but some answer here helped me.

array(3) { 
           [0]=> float(-0.12459619130796) 
           [1]=> float(-0.64018439966448) 
           [2]=> float(0)
         }

Then use if condition to stop looping

foreach($array as $key => $val){
           if($key == 0){ //the key is 0
               echo $key; //find the key
               echo $val; //get the value
           }
        }

Comments

0

I know, after so many years this could be a useless answer, but why not?

This is my personal implementation of a possible index_of using the same code as other answers but let the programmer to choose when and how the check will be done, supporting also complex checks.

if (!function_exists('index_of'))
{
    /**
     * @param iterable $haystack
     * @param callable $callback
     * @param mixed|null &$item
     * @return false|int|string
     */
    function index_of($haystack, $callback, &$item = null)
    {
        foreach($haystack as $_key => $_item) {
            if ($callback($_item, $_key) === true) {
                $item = $_item;
                return $_key;
            }
        }
        return false;
    }
}

Comments

-1
foreach( $arr as $k=>&$a) {
    if( $a['id'] == 4 )
        unset($arr[$k]);
}

5 Comments

You should never change the array you are currently iterating!
@fdomig What if there are more than one child with id 4?
@fdomig You can't say that for sure.
You should never touch the array itself while iterating anyway. You then better add each found index to a $found array and remove all keys afterwards.
Thanks for the tip. Will follow it. Though I still don't understand the point behind it. @fdomig

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.