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?

2
  • 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. 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. Commented Mar 6, 2013 at 11:36
  • If it is an id why not make that identifier the array/hash index in the first place? Commented Mar 6, 2013 at 11:39

2 Answers 2

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;

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

4 Comments

And there is no any reason to use for loop when foreach exists. So downvoted, sorry.
@Hast it's a good solution even though if it might not be optimal. You should suggest an edit rather than downvote.
@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 :)
@MattCain I downvoted because of quotes mostly, not because of loop choice.
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;
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.