2

I need to test if a specific key/value exists and then return the array index that the key/value is a member of without having to loop through each element and/or levels of the array. Is this possible?

 [0: 
     { regional:
          [ 0 :
               {
               ID: 1000
               someInfoA : valueA
               someInfoB : valueB
               }
          ]
          [ 1 :
               {
               ID: 1001
               someInfoA : valueA
               someInfoB : valueB
               }
          ]
          [ 2 :
               {
               ID: 1002
               someInfoA : valueA
               someInfoB : valueB
               }
          ]
          [ 3 :
               {
               ID: 1003
               someInfoA : valueA
               someInfoB : valueB
               }
          ]
     }
     { national : 
       [ ... ]
       [ ... ]
     }
] 

In this data example, I need to see if ID: 1002 exists and if it does, return the array index: [2], if not return false. i have seen various ways of just determining if the key/value exists but I haven't seen a non-loop method for returning the array index it belongs to.

2 Answers 2

5

You can do a combination of array_column() and array_search(). Have a look here.

$records = [
    [
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ],
    [
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ],
    [
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ],
    [
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    ]
];
$key = array_search(3245, array_column($records, 'id'));
echo $key;
Sign up to request clarification or add additional context in comments.

2 Comments

BRILLIANT! Thank you. I tested this and it works perfect. But what if the ID value isn't found - what does it return? I tested and $key was blank - is that an empty "" value?
If not found, it returns false
0

You can also use array_column() to create a new array with id as key. You have then all fields in direct access.

$arrWithIdAsKey = array_column($records, null, 'id');

echo "<pre>".var_export($arrWithIdAsKey,true)."</pre>";

Example Output:

array (
  2135 => 
  array (
    'id' => 2135,
    'first_name' => 'John',
    'last_name' => 'Doe',
  ),
  3245 => 
  array (
    'id' => 3245,
    'first_name' => 'Sally',
    'last_name' => 'Smith',
  ),
  5342 => 
  array (
    'id' => 5342,
    'first_name' => 'Jane',
    'last_name' => 'Jones',
  ),
  5623 => 
  array (
    'id' => 5623,
    'first_name' => 'Peter',
    'last_name' => 'Doe',
  ),
)

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.