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.
    – Milan
    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.

3
  • 1
    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. Jul 17, 2012 at 21:13
  • for me it was giving error of object not found so i did it as $value['id']
    – danish ali
    Mar 26, 2021 at 5: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 ;-) Jun 18, 2023 at 1: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.

5
  • 1
    wait .. $element is not an object?
    – Federkun
    Jul 17, 2012 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, 2012 at 19:28
  • $element is an instance of stdClass. See the question
    – Federkun
    Jul 17, 2012 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, 2012 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, 2012 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
0
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
  • 1
    This is almost exactly opposite of what I want :)
    – Milan
    Jul 18, 2012 at 12:50
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
  • 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, 2012 at 19:34
  • 1
    True, it depends on the situation and certainty of how many elements are there to unset. Though very useful function. Jul 17, 2012 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.

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]);
}
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.

0
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
           }
        }
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;
    }
}
-1
foreach( $arr as $k=>&$a) {
    if( $a['id'] == 4 )
        unset($arr[$k]);
}
5
  • You should never change the array you are currently iterating!
    – fdomig
    Jul 17, 2012 at 19:28
  • @fdomig What if there are more than one child with id 4?
    – hjpotter92
    Jul 17, 2012 at 19:30
  • @fdomig You can't say that for sure.
    – hjpotter92
    Jul 17, 2012 at 19:35
  • 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.
    – fdomig
    Jul 17, 2012 at 19:36
  • Thanks for the tip. Will follow it. Though I still don't understand the point behind it. @fdomig
    – hjpotter92
    Jul 17, 2012 at 19:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.