skip to Main Content

Here my array:

$array = [
    'key1' => [
        'first' => 'azerty',
        'second' => 'qwerty'
    ],
    'key2' => [
        'first' => 'hello',
        'second' => 'world'
    ]
];

With the value ‘qwerty’ I would like to retrieve the ‘key1’.

I looking for something like that:

$theKeyIWant = array_search('qwerty', array_column($array, 'second'));

But I get ‘0’, instead of ‘key1’ (and I know that’s how it works)

Anyone know how to adapt this code or know another code to get the key value?

4

Answers


  1. To solve this is to loop through the outer array and use array_search() to search for the value within each inner array.

    $value = 'qwerty';
    $theKeyIWant = null;
    
    foreach ($array as $key => $innerArray) {
      if (array_search($value, $innerArray) !== false) {
        $theKeyIWant = $key;
        break;
      }
    }
    
    echo $theKeyIWant; // Output: key1
    
    Login or Signup to reply.
  2. array_keys returns an array of an array’s keys.

    <?php
    
    $array = [
    'key1' => [
        'first' => 'azerty',
        'second' => 'qwerty'
    ],
    'key2' => [
        'first' => 'hello',
        'second' => 'world'
    ]
    ];
    $theKeyIWant = array_search('qwerty', array_column($array, 'second'));
    echo array_keys($array)[$theKeyIWant];
    ?>
    

    3V4l

    Login or Signup to reply.
  3. Slight modification to your code to combine the keys and column values:

    $theKeyIWant = array_search('qwerty', array_combine(array_keys($array), array_column($array, 'second')));
    
    Login or Signup to reply.
  4. The problem with seeking "something sexier" for this task is that if "sexier" means a "functional iterator", then that comes a cost of not being able to "return early" (doing unnecessary cycles).

    If you want a single-line function to call, you can build your own and put it in a helpers file somewhere in your project. My strong advice is to abandon "sexy" for this task and use a breakable foreach loop.

    Code: (Demo)

    function getRowKey($array, $column, $value) {
        foreach ($array as $key => $row) {
            if ($row[$column] === $value) {
                return $key;
            }
        }
        return null;
    }
    
    var_export(getRowKey($array, 'second', 'qwerty'));
    

    If you are going to perform repeated searches on the same array and the second column is guaranteed to contain unique values, then you can convert the array into a lookup array without losing any data. (Demo)

    function restructure($array, $columnToKey) {
        $result = [];
        foreach ($array as $key => $row) {
            $result[$row[$columnToKey]] = $row + ['oldKey' => $key];
        }
        return $result;
    }
    
    var_export(restructure($array, 'second')['qwerty']);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search