0

i have an array something like given below is it possible to find the key index of the array if i provide a slab id value in php?

Array
       (
           [0] => incentiveSlab Object
               (
                   [slabId] => 1
                   [templateId] => 1
                   [startPoint] => 0
                   [endPoint] => 1000000
                   [value] => 0
               )

           [1] => incentiveSlab Object
               (
                   [slabId] => 2
                   [templateId] => 1
                   [startPoint] => 1000000
                   [endPoint] => 2500000
                   [value] => 0.5
               )


       )
0

3 Answers 3

3

Something like that :

function getIndex($array, $slabId) {
    foreach($array as $index => $item) {
        if($item->slabId == $slabId)
            return $index;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

i was looking for built in functions
0

I will suggest, change your Data Structure

  • use slabId as Array_Index
  • Eg.

    Array

    (

       [0] => NULL
    
       [1] => incentiveSlab Object
           (
               [slabId] => 1
               [templateId] => 1
               [startPoint] => 0
               [endPoint] => 1000000
               [value] => 0
           )
    
       [2] => incentiveSlab Object
           (
               [slabId] => 2
               [templateId] => 1
               [startPoint] => 1000000
               [endPoint] => 2500000
               [value] => 0.5
           )
    

    )

Or if you have too much variance in slabId use Associative Array

Comments

0

The solution should return the index if it is found like the above answers. However, it should returns something else if there is no match, like other standard functions such as substr which returns false if there is no match. so Max answer may be modified, slightly, to be:

function getIndex($array, $slabId) {
    foreach($array as $index => $item) {
        if($item->slabId == $slabId)
            return $index;
    }
    return false; // or return -1
}

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.