PHP if in_array() how to get the key as well?

后端 未结 6 1410
死守一世寂寞
死守一世寂寞 2020-12-28 11:32

Struggling with a tiny problem.

I have an array:

Array
(
    [0] => 
    [6] => 6
    [3] => 5
    [2] => 7
)

I am chec

相关标签:
6条回答
  • 2020-12-28 11:59

    You could just use this http://www.php.net/manual/en/function.array-search.php

    $key = array_search(5, $array)
    if ($key !== false) {
    ...
    
    0 讨论(0)
  • 2020-12-28 12:03

    Maybe you want to use array_search instead, which returns false if the value is not found and the index if the value is found. Check out the description here

    0 讨论(0)
  • 2020-12-28 12:03

    In case anyone need it in array of arrrays. My case was this:

    I had an array like this:

    $myArray =
    
    array:3 [▼
      0 => array:3 [▼
        0 => 2
        1 => 0
        2 => "2019-07-21 23:59:59"
      ]
      1 => array:3 [▼
        0 => 3
        1 => 2
        2 => "2019-07-21 23:59:59"
      ]
      2 => array:3 [▼
        0 => 1
        1 => 1
        2 => "2019-07-21 23:59:59"
      ]
    ]
    

    And another one like this (an array of objects):

    $Array2 = 
    
    Collection {#771 ▼
      #items: array:12 [▼
        0 => {#1047 ▼
          +"id": 2
          +"name": "demografico"
          +"dict_key": "demographic"
          +"component": "Demographic"
          +"country_id": null
          +"created_at": null
          +"updated_at": null
        }
        1 => {#1041 ▶}
        2 => {#1040 ▶}
        etc...
    

    As the OP, I had to "do something" (use values in a html php template, my case Laravel with blade) with the key where some value was in the array. For my code, I had to use this:

    foreach($Array2 as $key => $item)
        if(false !== $key = array_search($item->id, array_column($myArray, 0))
        // Note that $key is overwritten
            <input type="number" class="form-control" id="{!! $item->id !!}" value="{{ $myArray[$key][1] }}">
    
    0 讨论(0)
  • 2020-12-28 12:13

    array_search() is what you are looking for.

    if (false !== $key = array_search(5, $array)) {
        //do something
    } else {
        // do something else
    }
    
    0 讨论(0)
  • 2020-12-28 12:13

    You can try

    if(in_array(5, $array))
    {
        $key = array_search(5, $array);
        echo $key;
    }
    

    this way you know it exists, and if it doesn't it doesn't cause notices, warnings, or fatal script errors depending on what your doing with that key there after.

    0 讨论(0)
  • 2020-12-28 12:24

    If you only need the key of the first match, use array_search():

    $key = array_search(5, $array);
    if ($key !== false) {
        // Found...
    }
    

    If you need the keys of all entries that match a specific value, use array_keys():

    $keys = array_keys($array, 5);
    if (count($keys) > 0) {
        // At least one match...
    }
    
    0 讨论(0)
提交回复
热议问题