2

Suppose you have the following array values assigned to a variable,

$erz = Array ( 
  [0] => stdClass Object ( [id] => 43 [gt] => 112.5 ) 
  [1] => stdClass Object ( [id] => 47 [gt] => 46 ) 
  [2] => stdClass Object ( [id] => 48 [gt] => 23.75 )
  [3] => stdClass Object ( [id] => 49 [gt] => 12.5 ) 
)

I need to be able to get the array index number given the id. So for instance I want to get 2 given id 48, or get 3 given id 49, etc. Is there a php command able to do this?

Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56
Marlboro Goodluck
  • 289
  • 1
  • 4
  • 12
  • If it is an `id` why not make that identifier the array/hash index in the first place? – VolkerK Mar 06 '13 at 11:39
  • You could try using a PhpLinq to do this, it's very similar to the .Net version. Look at the following link for more info. http://tech.pro/tutorial/797/basic-linq-syntax-in-php-with-phplinq It may not be exactly what you're looking for to get the index but it will return the whole item. – Stanley_A Mar 06 '13 at 11:36

2 Answers2

1

I dont think there is but its easy to set up your own function..

function findArrayIndex($arr, $searchId) {

    $arrLen = count($arr);
    for($i=0; $i < $arrLen; $i++) {
       if($arr[$i][id] == $searchId) return $i;
    }

    return -1;

}
cowls
  • 24,013
  • 8
  • 48
  • 78
  • And there is no any reason to use for loop when foreach exists. So downvoted, sorry. – ozahorulia Mar 06 '13 at 11:38
  • @Hast it's a good solution even though if it might not be optimal. You should suggest an edit rather than downvote. – Matt Cain Mar 06 '13 at 11:50
  • @cowls using of for loop instead of foreach in such cases considered a bad practice actually. And with foreach I also have the index in a separate variable, look at the my answer :) – ozahorulia Mar 06 '13 at 11:54
  • @MattCain I downvoted because of quotes mostly, not because of loop choice. – ozahorulia Mar 06 '13 at 11:55
0

No, there is no such funcion. There is an array_search() actually, but you can't use it with objects. For example, here has been asked a simmilar question: PHP - find entry by object property from a array of objects

So you have to make your own loop:

$result = null;
$givenID = 43;
foreach ($erz as $key => $element)
{
    if ($element->id == $givenID)
        $result = $key;
}
Community
  • 1
  • 1
ozahorulia
  • 9,798
  • 8
  • 48
  • 72