skip to Main Content

I´ve isolated a problem I´m having in a complex code and was able to replicate the issue. Let´s say I have the following array:

$categoriesFiltersGenericCheck[2] = [
    'id' => 2214,
    'sort_order' => '0.000000000000000000000000000000',
    'date_creation' => '2023-09-10 11:17:41',
    'date_edit' => '2023-09-10 11:17:41',
    'id_filters_generic' => 2054,
    'id_filter_index' => 101,
    'id_record' => 2212,
    'notes' => '',
];

Then, I use array_search to grab the array key in which the search matches:

$categoriesFiltersGenericCheckKeyMatch = array_search(2054, array_column($categoriesFiltersGenericCheck, 'id_filters_generic'));

I´m expecting to get 2 as a result. However, it´s returning 0

Demo: https://onlinephp.io/c/967b9b

Anyone knows what I might be missing? I´ve done this same pattern in other parts of my code and worked, strangely enough.

Configuration:
PHP 8.0.16

2

Answers


  1. array_column($categoriesFiltersGenericCheck, 'id_filters_generic') returns this:

    array(1) {
      [0]=>
      int(2054)
    }
    

    Note that the key is lost (which is expected behavior). So naturally array_search() will return 0.

    A simple and efficient working implementation is this:

    function search($arr, $id)
    {
        foreach($arr as $key => $val)
        {
            if($val['id_filters_generic'] == $id)
                return $key;
        }
        return null;
    }
    
    echo search($categoriesFiltersGenericCheck, 2054);
    
    Login or Signup to reply.
  2. $categoriesFiltersGenericCheck[2] = [
      'id'                 => 2214,
      'sort_order'         => '0.000000000000000000000000000000',
      'date_creation'      => '2023-09-10 11:17:41',
      'date_edit'          => '2023-09-10 11:17:41',
      'id_filters_generic' => 2054,
      'id_filter_index'    => 101,
      'id_record'          => 2212,
      'notes'              => '',
    ];
    
    $categoriesFiltersGenericCheckKeyMatch =
      array_key_first(
        array_filter(
          $categoriesFiltersGenericCheck,
          fn($item) => $item['id_filters_generic'] === 2054
        )
      );
    
    echo $categoriesFiltersGenericCheckKeyMatch;   // Output: 2
    

    $categoriesFiltersGenericCheckKeyMatch will be null should the filter condition evaluate to false for all entries.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search