jreed121
jreed121

Reputation: 2097

php determine position of array key relative to another key

I was wondering if it was possible to determine what position a key in an array is in relation to another key. I have a large multidimensional array and I need perform Function A when the key [E14_21] comes before [E14_20] and I need to perform a different Function B if not...

//perform Function A if:
[E14_20_0] => Array
    (
        [E14_21] => 3235
        [E14_20] => 96
    )
//Perform Function B if:
[E14_20_0] => Array
    (
        [E14_20] => 96
        [E14_21] => 3235
    )

Upvotes: 1

Views: 390

Answers (2)

jcoby
jcoby

Reputation: 4260

You can do something like:

$keys = array_keys($E14_20_0);
if(array_search("E14_21", $keys) < array_search("E14_20", $keys)) {
  // function A
} else {
  // function B
}

You will of course need to add some sanity checks to make sure both keys exist in the array, etc.

Upvotes: 2

Surreal Dreams
Surreal Dreams

Reputation: 26380

It seems you might do this:

reset($E14_20_0);
first = each($E14_20_0);
second = each($E14_20_0);

if(first['key'] > second['key'])
{
    //do something
}

This is very specific to your example, but it might help you get started.

reset() will reset the array pointer to the "first" element. each() returns the key and value of the array based on the pointer and advances the pointer. Then you can compare keys and perform your logic.

Upvotes: 1

Related Questions