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

Struggling with a tiny problem.

I have an array:

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

I am checking if a set value is in the array.

if(in_array(5, $array)) {
//do something
} else {
// do something else
}

The thing is, when it find the value 5 in array, I really need the key to work with in my "do something".

In this case I need to set:

$key = 3;

(key from the found value in_array).

Any suggestions?



Solution 1:[1]

array_search() is what you are looking for.

if (false !== $key = array_search(5, $array)) {
    // found!
} else {
    // not found!
}

Solution 2:[2]

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...
}

Solution 3:[3]

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

$key = array_search(5, $array)
if ($key !== false) {
...

Solution 4:[4]

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.

Solution 5:[5]

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

Solution 6:[6]

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] }}">

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akhilesh B Chandran
Solution 2 Niko
Solution 3
Solution 4 Niko
Solution 5 ryanbwork
Solution 6 pmiranda