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?

helle
  • 11,183
  • 9
  • 56
  • 83
Milan
  • 969
  • 2
  • 16
  • 34
  • Weird thing that after unsetting array item, it breaks json_encode so output becomes unusable. – Milan Jul 18 '12 at 12:29

11 Answers11

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.

fdomig
  • 4,417
  • 3
  • 26
  • 39
  • 1
    I'm not sure about the rule of not removing array element while iterating it. In another [question](http://stackoverflow.com/questions/2304570/how-to-delete-object-from-array-inside-foreach-loop) 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. – Marcin Szulc Jul 17 '12 at 21:13
  • for me it was giving error of object not found so i did it as `$value['id']` – danish ali Mar 26 '21 at 05:44
  • @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 ;-) – Phil Rykoff Jun 18 '23 at 01:38
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.

Lix
  • 47,311
  • 12
  • 103
  • 131
  • 1
    wait .. $element is not an object? – Federkun Jul 17 '12 at 19:24
  • @lax - I don't follow...What do you mean? The variable `$element` refers to an element within the array... – Lix Jul 17 '12 at 19:28
  • $element is an instance of stdClass. See the question – Federkun Jul 17 '12 at 19:39
  • @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 Jul 17 '12 at 20:27
  • @Lix thanks, your answer is also great. I picked other one only because I had to pick one and that was more "complete". – Milan Jul 18 '12 at 12:02
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
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);
half-a-nerd
  • 313
  • 6
  • 21
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);
Marcin Szulc
  • 1,171
  • 1
  • 10
  • 21
  • This is a good solution, however you are iterating over the whole collection although it is not necessary most of the times. – fdomig Jul 17 '12 at 19:34
  • 1
    True, it depends on the situation and certainty of how many elements are there to unset. Though very useful function. – Marcin Szulc Jul 17 '12 at 19:37
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.

Baylor Rae'
  • 3,995
  • 20
  • 39
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]);
}
Federkun
  • 36,084
  • 8
  • 78
  • 90
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.

dleviathan
  • 87
  • 1
  • 2
  • 17
ThangTD
  • 1,586
  • 17
  • 16
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
           }
        }
Khamad Ali
  • 33
  • 1
  • 11
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;
    }
}
Matteo Gaggiano
  • 1,254
  • 15
  • 28
-1
foreach( $arr as $k=>&$a) {
    if( $a['id'] == 4 )
        unset($arr[$k]);
}
hjpotter92
  • 78,589
  • 36
  • 144
  • 183