kevin seda
kevin seda

Reputation: 406

Get the index of an array based on keys

I have an array with an index. The index is not static and keeps changing.

$fields = [
  11 => array (
    'fieldId' => 'ORStreet',
    'type' => 'TEXT',
    'value' => 'Postbus 52',
  ),
];

Index of the above one is 11. But sometimes it becomes a different number. One thing that always stays the same is the fieldId. How can i get the index of this array by only knowing the field id.

This above array is a child of the main array called 'fields'.

In my head i have something like this:

Loop through the main array called fields > if you find an array with fieliD => ORStreet. Return the index of that array.

If its not possible to get an index this way, i wouldnt mind if I got the 'value' => 'Postbus52' key-pair.

Upvotes: 0

Views: 87

Answers (3)

miken32
miken32

Reputation: 42676

One more possibility:

$result = array_keys(
    array_combine(array_keys($fields), array_column($fields, "fieldId")),
    "ORStreet"
);

array_column() extracts all the fieldId values, and then array_keys() searches for your desired value, returning the relevant array keys.

Note this will return an array of keys. If you only want the first key, this will return it as an integer:

$result = array_search(
    "ORStreet",
    array_combine(array_keys($fields), array_column($fields, "fieldId"))
);

Upvotes: 1

yetanothersourav
yetanothersourav

Reputation: 364

<?php
$arr = [
    [
      'fieldId' => 'ORStreet',
      'type' => 'TEXT',
      'value' => 'Postbus 52',
            ],
    [
      'fieldId' => 'vbnm',
      'type' => 'TEXT',
      'value' => 'Postbus 52',
            ],
    [
      'fieldId' => 'ORStreet',
      'type' => 'TEXT',
      'value' => 'Postbus 52',
    ]                               
    ];
    shuffle($arr);
    foreach ($arr as $key => $value) {
        if(array_key_exists("fieldId", $value) && $value["fieldId"] === "ORStreet"){
            echo $key;
            break;
        }
    }
?>

I have used shuffle method to simulate randomness of the array. Then I have loop through the array to match fieldId with specified value(ORStreet) . If it got match then the loop will terminates and display the index.

Another Way:

$filteredArr = array_pop(array_filter($arr, function ($a){
  return array_key_exists("fieldId", $a) && $a["fieldId"] === "ORStreet";
}));

Upvotes: 1

Mohammad
Mohammad

Reputation: 21489

You can use combination of array_map() and array_flip()

$index = array_flip(array_map(function($val){
    return $val["fieldId"];
}, $arr));
echo $index["ORStreet"];
// output: 11

Check result in demo

Upvotes: 1

Related Questions