Sridhar G
Sridhar G

Reputation: 89

How to find the position of key value in an array

I have an array with user id and transaction details sorted based on transaction. Now I need to find the position of key value

Array
(
    [0] => Array
        (
            [userid] => 3
            [transaction] => 1878
        )

    [1] => Array
        (
            [userid] => 2
            [transaction] => 416
        )

    [2] => Array
        (
            [userid] => 5
            [transaction] => 353
        )

    [3] => Array
        (
            [userid] => 4
            [transaction] => 183
        )
)

When I give user id 4 then it should return 3

Upvotes: 0

Views: 117

Answers (4)

Calos
Calos

Reputation: 1942

First, use array_column() to fetch all userid, then use array_search() to retrieve array key.

$searchId = 4;
echo array_search( $searchId, array_column($array, 'userid') ) );

Upvotes: 1

Progrock
Progrock

Reputation: 7485

It's trivial to build your own map:

<?php

$items = 
[
    'foo' =>
        [
            'id' => 23,
        ],
    'bar' =>
        [
            'id' => 47
        ]
];

foreach($items as $k=>$v)
    $ids_keys[$v['id']] = $k;

echo $ids_keys[47];

Output:

bar

Upvotes: 0

yqlim
yqlim

Reputation: 7080

I prefer Calos's answer.

The code below imitates JavaScript's Array.prototype.findIndex to achieve what you need. Using this approach you can have more flexibility in searching the array by using a callback function, similar to how JavaScript has done it.

You can also easily reuse it in other parts of your code.

$data = [
    [
        'userid' => 3,
        'transaction' => 1878
    ],
    [
        'userid' => 2,
        'transaction' => 416
    ],
    [
        'userid' => 5,
        'transaction' => 353
    ],
    [
        'userid' => 4,
        'transaction' => 183
    ]
];

function findIndex($array, $method){
    foreach($array as $index => $value){
        if ($method($value, $index, $array) === true){
            return $index;
        }
    }
}

echo findIndex($data, function($arr){ 
    return $arr['userid'] == 5;
});

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520928

I might just iterate the outer array here and the check the key values:

$pos = -1;
for ($i = 0; $i < count($array); $i++) {
    if ($array[$i]['userid'] == 4) {
        $pos = $i;
    }
}

if ($pos == -1) {
    echo "user not found";
}
else {
    echo "user found at position " . $pos;
}

Upvotes: 1

Related Questions